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/97/0x670cbE8C92cEddc985F8cB4eacd57Abfc6BbA471/sources/project_/contracts/diamond/libraries/LibTrading.sol
slippage = (OiLong + qty) price / depthAboveUsd slippage = (OiLong + qty) price / depthBelowUsd
function _slippagePrice(address pairBase, uint256 marketPrice, uint256 qty, bool isLong, LibPairsManager.SlippageConfig memory sc) private view returns (uint256) { if (isLong) { uint slippage = sc.slippageLongP; if (sc.slippageType == IPairsManager.SlippageType.ONE_PERCENT_DEPTH) { slippage = (tradingStorage().pairPositionInfos[pairBase].longQty + qty) * marketPrice * Constants.BASIS_POINTS_DIVISOR / sc.onePercentDepthAboveUsd; } return marketPrice * (Constants.BASIS_POINTS_DIVISOR + slippage) / Constants.BASIS_POINTS_DIVISOR; uint slippage = sc.slippageShortP; if (sc.slippageType == IPairsManager.SlippageType.ONE_PERCENT_DEPTH) { slippage = (tradingStorage().pairPositionInfos[pairBase].shortQty + qty) * marketPrice * Constants.BASIS_POINTS_DIVISOR / sc.onePercentDepthBelowUsd; } return marketPrice * (Constants.BASIS_POINTS_DIVISOR - slippage) / Constants.BASIS_POINTS_DIVISOR; } }
3,270,370
./partial_match/1/0xcc3C54B95f3f1867A43009B80ed4DD930E3cE2F7/sources/lib/solidity-utils/src/contracts/create3/Create3.sol
Computes the resulting address of a contract deployed using address(this) and the given `_salt` salt Salt of the contract creation, resulting address will be derivated from this value only return address of the deployed contract, reverts on error The address creation formula is: keccak256(rlp([keccak256(0xff ++ address(this) ++ _salt ++ keccak256(childBytecode))[12:], 0x01]))/
function addressOf(bytes32 salt) internal view returns (address) { return addressOfWithPreDeployedFactory(salt, address(this)); }
2,800,848
./full_match/1/0x025030BdAa159f281cAe63873E68313a703725A5/sources/contracts/gelato_actions/gnosis/ActionPlaceOrderBatchExchange.sol
Will be called by GelatoActionPipeline if Action.dataFlow.InAndOut => do not use for _actionData encoding
function execWithDataFlowInAndOut( bytes calldata _actionData, bytes calldata _inFlowData ) external payable virtual override returns (bytes memory) { (address sellToken, uint128 sellAmount) = _handleInFlowData(_inFlowData); (address origin, address buyToken, uint128 buyAmount, uint32 batchDuration) = _extractReusableActionData(_actionData); action(origin, sellToken, sellAmount, buyToken, buyAmount, batchDuration); return abi.encode(sellToken, sellAmount); }
9,651,432
pragma solidity 0.5.10; contract Context { constructor () internal { } function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; return msg.data; } } interface IERC20 { function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(a, b, "SafeMath: subtraction overflow"); } function SUB97(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL111(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV358(a, b, "SafeMath: division by zero"); } function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD464(a, b, "SafeMath: modulo by zero"); } function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(_MSGSENDER793(), recipient, amount); return true; } function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, amount); return true; } function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(sender, recipient, amount); _APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue)); return true; } function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER927(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB97(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD803(amount); emit TRANSFER432(sender, recipient, amount); } function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD803(amount); _balances[account] = _balances[account].ADD803(amount); emit TRANSFER432(address(0), account, amount); } function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB97(amount); emit TRANSFER432(account, address(0), amount); } function _APPROVE171(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL431(owner, spender, amount); } function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN826(account, amount); _APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance")); } } library BytesLib { function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory tempBytes; assembly { tempBytes := mload(0x40) let length := mload(_preBytes) mstore(tempBytes, length) let mc := add(tempBytes, 0x20) let end := add(mc, length) for { let cc := add(_preBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) mc := end end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) )) } return tempBytes; } function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) switch add(lt(slength, 32), lt(newlength, 32)) case 2 { sstore( _preBytes_slot, add( fslot, add( mul( div( mload(add(_postBytes, 0x20)), exp(0x100, sub(32, mlength)) ), exp(0x100, sub(32, newlength)) ), mul(mlength, 2) ) ) ) } case 1 { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + _length), "Slice out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) mstore(0x40, and(add(mc, 31), not(31))) } default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 20), "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32), "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let length := mload(_preBytes) switch eq(length, mload(_postBytes)) case 1 { let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { if iszero(eq(mload(mc), mload(cc))) { success := 0 cb := 0 } } } default { success := 0 } } return success; } function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) switch eq(slength, mlength) case 1 { if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { success := 0 } } default { let cb := 1 mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { success := 0 cb := 0 } } } } } default { success := 0 } } return success; } function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING bytes memory tempEmptyStringTest = bytes(_source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } } library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING if (uint8(_flag[0]) == 0xff) { return 8; } if (uint8(_flag[0]) == 0xfe) { return 4; } if (uint8(_flag[0]) == 0xfd) { return 2; } return 0; } function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _start = _b.length.SUB97(_num); return _b.SLICE479(_start, _num); } function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571(); } function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); _offset = _offset + _len; } _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); return _vin.SLICE479(_offset, _len); } function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00"); } function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input); bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_beSequence)); } function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen); } function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING bytes memory _varIntTag = _input.SLICE479(36, 1); uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag); uint256 _len; if (_varIntDataLen == 0) { _len = uint8(_varIntTag[0]); } else { _len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen))); } return (_varIntDataLen, _len); } function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(37, 4); } function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input); bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_inputeSequence)); } function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 36); } function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 32).TOBYTES32571(); } function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input)); bytes memory _beId = REVERSEENDIANNESS18(_leId); return _beId.TOBYTES32571(); } function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(32, 4); } function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leIndex = EXTRACTTXINDEXLE408(_input); bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex); return uint32(BYTESTOUINT790(_beIndex)); } function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _len = uint8(_output.SLICE479(8, 1)[0]); require(_len < 0xfd, "Multi-byte VarInts not supported"); return _len + 8 + 1; } function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); _offset = _offset + _len; } _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); return _vout.SLICE479(_offset, _len); } function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(8, 1); } function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(0, 8); } function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING bytes memory _leValue = EXTRACTVALUELE862(_output); bytes memory _beValue = REVERSEENDIANNESS18(_leValue); return uint64(BYTESTOUINT790(_beValue)); } function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.SLICE479(10, 1); return _output.SLICE479(11, BYTESTOUINT790(_dataLen)); } function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (uint8(_output.SLICE479(9, 1)[0]) == 0) { uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2; if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) { return hex""; } return _output.SLICE479(11, _len); } else { bytes32 _tag = keccak256(_output.SLICE479(8, 3)); if (_tag == keccak256(hex"1976a9")) { if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 || keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) { return hex""; } return _output.SLICE479(12, 20); } else if (_tag == keccak256(hex"17a914")) { if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) { return hex""; } return _output.SLICE479(11, 20); } } return hex""; } function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]); if (_nIns >= 0xfd || _nIns == 0) { return false; } for (uint8 i = 0; i < _nIns; i++) { _offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset)); if (_offset > _vin.length) { return false; } } return _offset == _vin.length; } function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]); if (_nOuts >= 0xfd || _nOuts == 0) { return false; } for (uint8 i = 0; i < _nOuts; i++) { _offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset)); if (_offset > _vout.length) { return false; } } return _offset == _vout.length; } function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(36, 32); } function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header)); } function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING bytes memory _m = _header.SLICE479(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING return diff1_target719.DIV358(_target); } function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(4, 32); } function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header)); } function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(68, 4); } function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header)))); } function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header)); } function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return HASH256986(abi.encodePacked(_a, _b)); } function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING if (_proof.length % 32 != 0) { return false; } if (_proof.length == 32) { return true; } if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571(); bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571(); for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current)); } else { _current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } function RETARGETALGORITHM78( //inject NONSTANDARD NAMING uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp); if (_elapsedTime < retarget_period820.DIV358(4)) { _elapsedTime = retarget_period820.DIV358(4); } if (_elapsedTime > retarget_period820.MUL111(4)) { _elapsedTime = retarget_period820.MUL111(4); } uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime); return _adjusted.DIV358(retarget_period820).MUL111(65536); } } interface FundsInterface { function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING } interface SalesInterface { function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING } interface CollateralInterface { function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING } contract DSMath { function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x + y) >= x); } function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x - y) <= x); } function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require(y == 0 || (z = x * y) / y == x); } function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING require(b > 0); c = a / b; } function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), col735 / 2) / col735; } function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), wad510 / 2) / wad510; } function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), ray271 / 2) / ray271; } function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, col735), y / 2) / y; } function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, wad510), y / 2) / y; } function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, ray271), y / 2) / y; } function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = n % 2 != 0 ? x : ray271; for (n /= 2; n != 0; n /= 2) { x = RMUL965(x, x); if (n % 2 != 0) { z = RMUL965(z, x); } } } } contract Medianizer { function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING function READ913() external returns (bytes32); //inject NONSTANDARD NAMING function POKE561() external; //inject NONSTANDARD NAMING function POKE561(bytes32) external; //inject NONSTANDARD NAMING function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING } contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; mapping (bytes32 => SecretHashes) public secretHashes; mapping (bytes32 => Bools) public bools; mapping (bytes32 => bytes32) public fundIndex; mapping (bytes32 => uint256) public repayments; mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; ERC20 public token; uint256 public decimals; address deployer; struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].borrower; } function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].lender; } function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].arbiter; } function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].createdAt, approve_exp_threshold840); } function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, accept_exp_threshold947); } function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443); } function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699); } function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].principal; } function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].interest; } function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].fee; } function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].penalty; } function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return col.COLLATERAL382(loan); } function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.REFUNDABLECOLLATERAL879(loan); } function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.SEIZABLECOLLATERAL368(loan); } function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYREFUNDABLECOLLATERAL760(loan); } function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYSEIZABLECOLLATERAL228(loan); } function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return repayments[loan]; } function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].liquidationRatio; } function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(PRINCIPAL566(loan), INTEREST523(loan)); } function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDTOLENDER7(loan), FEE426(loan)); } function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan)); } function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return SUB97(OWEDFORLOAN262(loan), REPAID307(loan)); } function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].funded; } function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].approved; } function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].withdrawn; } function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].sale; } function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].paid; } function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].off; } function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return MUL111(x, (10 ** SUB97(18, decimals))); } function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return DIV358(x, (10 ** SUB97(18, decimals))); } function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING return borrowerLoans[borrower_].length; } function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING return lenderLoans[lender_].length; } function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735)); } function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return CMUL87(price, COLLATERAL382(loan)); } function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan)); } function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317); } function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan); } constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed"); } function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } function CREATE943( //inject NONSTANDARD NAMING uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = ADD803(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan); col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit CREATE22(loan); } function SETSECRETHASHES742( //inject NONSTANDARD NAMING bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens"); emit FUNDLOAN50(loan); } function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit APPROVE490(loan); } function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);} emit WITHDRAW160(loan, secretA1); } function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.repay: Loan cannot be inactive"); require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = ADD803(amount, repayments[loan]); if (REPAID307(loan) == OWEDFORLOAN262(loan)) { bools[loan].paid = true; if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} } emit REPAY404(loan, amount); } function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.refund: Loan cannot be inactive"); require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens"); emit REFUND289(loan); } function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING ACCEPT922(loan, secret); emit CANCEL833(loan, secret); } function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); CLOSE691(loan); emit CANCEL833(loan, bytes32(0)); } function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; CLOSE691(loan); emit ACCEPT489(loan, secret); } function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING bools[loan].off = true; loans[loan].closedTimestamp = now; if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], loans[loan].principal); } } else { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan)); } require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); if (sales.NEXT199(loan) == 0) { if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } } else { require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached"); require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.NEXT199(loan); sale_ = sales.CREATE943( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} emit LIQUIDATE130(loan, secretHash, pubKeyHash); } } interface CTokenInterface { function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface CERC20Interface { function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING } interface ERC20Interface { function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface TrollerInterface { function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING } contract Helpers is DSMath { address public comptroller; function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING return comptroller; } function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117()); address[] memory markets = troller.GETASSETSIN764(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.ENTERMARKETS395(toEnter); } } function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING ERC20Interface erc20Contract = ERC20Interface(erc20); uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.APPROVE357(to, 2**255); } } } contract ALCompound is Helpers { function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING ENTERMARKET780(cErc20); ERC20Interface token = ERC20Interface(erc20); uint toDeposit = token.BALANCEOF227(address(this)); if (toDeposit > tokenAmt) { toDeposit = tokenAmt; } CERC20Interface cToken = CERC20Interface(cErc20); SETAPPROVAL391(erc20, toDeposit, cErc20); assert(cToken.MINT386(toDeposit) == 0); } function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); SETAPPROVAL391(cErc20, 10**50, cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666()); if (tokenToReturn > tokenAmt) { tokenToReturn = tokenAmt; } require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong"); } function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); if (toBurn > cTokenAmt) { toBurn = cTokenAmt; } SETAPPROVAL391(cErc20, toBurn, cErc20); require(cToken.REDEEM46(toBurn) == 0, "something went wrong"); } } contract Funds is DSMath, ALCompound { Loans loans; uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (address => bytes32[]) public secretHashes; mapping (address => uint256) public secretHashIndex; mapping (address => bytes) public pubKeys; mapping (bytes32 => Fund) public funds; mapping (address => bytes32) public fundOwner; mapping (bytes32 => Bools) public bools; uint256 public fundIndex; uint256 public lastGlobalInterestUpdated; uint256 public tokenMarketLiquidity; uint256 public cTokenMarketLiquidity; uint256 public marketLiquidity; uint256 public totalBorrow; uint256 public globalInterestRateNumerator; uint256 public lastUtilizationRatio; uint256 public globalInterestRate; uint256 public maxUtilizationDelta; uint256 public utilizationInterestDivisor; uint256 public maxInterestRateNumerator; uint256 public minInterestRateNumerator; uint256 public interestUpdateDelay; uint256 public defaultArbiterFee; ERC20 public token; uint256 public decimals; CTokenInterface public cToken; bool compoundSet; address deployer; struct Fund { address lender; uint256 minLoanAmt; uint256 maxLoanAmt; uint256 minLoanDur; uint256 maxLoanDur; uint256 fundExpiry; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; address arbiter; uint256 balance; uint256 cBalance; } struct Bools { bool custom; bool compoundEnabled; } event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING constructor( ERC20 token_, uint256 decimals_ ) public { require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero"); require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero"); deployer = msg.sender; token = token_; decimals = decimals_; utilizationInterestDivisor = 10531702972595856680093239305; maxUtilizationDelta = 95310179948351216961192521; globalInterestRateNumerator = 95310179948351216961192521; maxInterestRateNumerator = 182321557320989604265864303; minInterestRateNumerator = 24692612600038629323181834; interestUpdateDelay = 86400; defaultArbiterFee = 1000000000236936036262880196; globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); } function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this"); require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set"); require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero"); loans = loans_; require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved"); } function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending"); require(!compoundSet, "Funds.setCompound: Compound address has already been set"); require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero"); require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero"); cToken = cToken_; comptroller = comptroller_; compoundSet = true; } function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this"); require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero"); utilizationInterestDivisor = utilizationInterestDivisor_; } function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this"); require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero"); maxUtilizationDelta = maxUtilizationDelta_; } function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this"); require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero"); globalInterestRateNumerator = globalInterestRateNumerator_; } function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this"); require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero"); globalInterestRate = globalInterestRate_; } function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this"); require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero"); maxInterestRateNumerator = maxInterestRateNumerator_; } function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this"); require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero"); minInterestRateNumerator = minInterestRateNumerator_; } function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this"); require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero"); interestUpdateDelay = interestUpdateDelay_; } function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this"); require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%"); defaultArbiterFee = defaultArbiterFee_; } function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].lender; } function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanAmt;} else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));} } function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].maxLoanAmt;} else {return default_max_loan_amt507;} } function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanDur;} else {return default_min_loan_dur981;} } function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].maxLoanDur; } function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].fundExpiry; } function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].interest;} else {return globalInterestRate;} } function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].penalty;} else {return default_liquidation_penalty756;} } function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].fee;} else {return defaultArbiterFee;} } function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].liquidationRatio;} else {return default_liquidation_ratio475;} } function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].arbiter; } function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666()); } else { return funds[fund].balance; } } function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING if (compoundSet) { return cToken.EXCHANGERATECURRENT666(); } else { return 0; } } function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING return bools[fund].custom; } function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING return secretHashes[addr_].length; } function CREATE943( //inject NONSTANDARD NAMING uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years" ); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].arbiter = arbiter_; bools[fund].custom = false; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function CREATECUSTOM959( //inject NONSTANDARD NAMING uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 liquidationRatio_, uint256 interest_, uint256 penalty_, uint256 fee_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years" ); require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur"); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; funds[fund].arbiter = arbiter_; bools[fund].custom = true; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens"); if (bools[fund].compoundEnabled) { MINTCTOKEN703(address(token), address(cToken), amount_); uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666()); funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);} } else { funds[fund].balance = ADD803(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit DEPOSIT856(fund, amount_); } function UPDATE438( //inject NONSTANDARD NAMING bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_ ) public { require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund"); require( ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66, "Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years" ); funds[fund].maxLoanDur = maxLoanDur_; funds[fund].fundExpiry = fundExpiry_; funds[fund].arbiter = arbiter_; emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_); } function UPDATECUSTOM705( //inject NONSTANDARD NAMING bytes32 fund, uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 interest_, uint256 penalty_, uint256 fee_, uint256 liquidationRatio_, address arbiter_ ) external { require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund"); require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur"); UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_); funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; } function REQUEST711( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_, bytes32[8] calldata secretHashes_, bytes calldata pubKeyA_, bytes calldata pubKeyB_ ) external returns (bytes32 loanIndex) { require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request"); require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance"); require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt"); require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt"); require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur"); require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry"); require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero"); require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero"); require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero"); require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero"); require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero"); loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_); LOANUPDATEMARKETLIQUIDITY912(fund, amount_); loans.FUND172(loanIndex); emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); } function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING WITHDRAWTO298(fund, amount_, msg.sender); } function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens"); require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance"); if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit WITHDRAW160(fund, amount_, recipient_); } function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING for (uint i = 0; i < secretHashes_.length; i++) { secretHashes[msg.sender].push(secretHashes_[i]); } } function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING pubKeys[msg.sender] = pubKey_; } function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured"); require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled"); require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound"); uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); MINTCTOKEN703(address(token), address(cToken), funds[fund].balance); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore); tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance); cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn); bools[fund].compoundEnabled = true; funds[fund].balance = 0; funds[fund].cBalance = cTokenToReturn; emit ENABLECOMPOUND170(fund); } function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled"); require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound"); uint256 balanceBefore = token.BALANCEOF227(address(this)); REDEEMCTOKEN224(address(cToken), funds[fund].cBalance); uint256 balanceAfter = token.BALANCEOF227(address(this)); uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore); tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn); cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance); bools[fund].compoundEnabled = false; funds[fund].cBalance = 0; funds[fund].balance = tokenToReturn; emit DISABLECOMPOUND118(fund); } function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this"); totalBorrow = SUB97(totalBorrow, amount_); } function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725())); if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) { uint256 utilizationRatio; if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));} if (utilizationRatio > lastUtilizationRatio) { uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio); globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } else { uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio); globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); lastGlobalInterestUpdated = now; lastUtilizationRatio = utilizationRatio; } } function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_); } function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING if (value == 0) { if (addNow) { return now + max_loan_length66; } return max_loan_length66; } return value; } function CREATELOAN338( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_ ) private returns (bytes32 loanIndex) { loanIndex = loans.CREATE943( now + loanDur_, [borrower_, LENDER92(fund), funds[fund].arbiter], [ amount_, CALCINTEREST818(amount_, INTEREST523(fund), loanDur_), CALCINTEREST818(amount_, PENALTY434(fund), loanDur_), CALCINTEREST818(amount_, FEE426(fund), loanDur_), collateral_, LIQUIDATIONRATIO684(fund), requestTimestamp_ ], fund ); } function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING bytes32 fund, bytes32 loan, bytes32[8] memory secretHashes_, bytes memory pubKeyA_, bytes memory pubKeyB_ ) private { loans.SETSECRETHASHES742( loan, [ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ], [ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ], GETSECRETHASHESFORLOAN447(ARBITER4(fund)), pubKeyA_, pubKeyB_, pubKeys[ARBITER4(fund)] ); } function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) { totalBorrow = ADD803(totalBorrow, amount_); CALCGLOBALINTEREST773(); } } function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4); require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated"); return [ secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)] ]; } }
inject NONSTANDARD NAMING
function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) {
1,784,168
./full_match/5/0x8cc4E47adB9D01070c6aC41420355F33FA543b59/sources/contracts/upgrades/GraphProxyAdmin.sol
Returns the pending implementation of a proxy. This is needed because only the proxy admin can query it. return The address of the pending implementation of the proxy./ We need to manually run the static call since the getter cannot be flagged as view bytes4(keccak256("pendingImplementation()")) == 0x396f7b23
function getProxyPendingImplementation(IGraphProxy _proxy) public view returns (address) { (bool success, bytes memory returndata) = address(_proxy).staticcall(hex"396f7b23"); require(success); return abi.decode(returndata, (address)); }
1,895,924
./full_match/80001/0x2d3B52Ab8233f29c7F189B6AAbD4AF8de3036cC4/sources/contracts/mixins/MixinKeys.sol
Modify the expirationTimestamp of a key by a given amount. _tokenId The ID of the key to modify. _deltaT The amount of time in seconds by which to modify the keys expirationTimestamp _addTime Choose whether to increase or decrease expirationTimestamp (false == decrease, true == increase) Throws if owner does not have a valid key./ append to valid key add from now if key is expired
function _timeMachine( uint _tokenId, uint256 _deltaT, bool _addTime ) internal { _isKey(_tokenId); uint formerTimestamp = _keys[_tokenId].expirationTimestamp; if (_addTime) { if (formerTimestamp > block.timestamp) { _keys[_tokenId].expirationTimestamp = formerTimestamp + _deltaT; _keys[_tokenId].expirationTimestamp = block.timestamp + _deltaT; } _keys[_tokenId].expirationTimestamp = formerTimestamp - _deltaT; } emit ExpirationChanged( _tokenId, _keys[_tokenId].expirationTimestamp, _deltaT, _addTime ); }
9,435,274
pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; contract IAuthCenter { function getAccountManager() public returns (address) ; function getAuthManager() public returns (address); //用于调用方鉴权, callee is externalAccount function check(address caller, address callee, bytes key) public view returns (bool); function checkWithSign(address callee, bytes key, bytes args, bytes32[4] sign) public view returns (address, bool); //用于调用方鉴权, callee is UserAccount.getData() function check2(address caller, address org, address callee, bytes key) public view returns (bool) ; function check2WithSign(address org, address callee, bytes key, bytes args, bytes32[4] sign) public view returns (address, bool); //管理方管理key权限 function addKeyType(bytes key, bytes value) public returns (bool) ; function removeKeyType(bytes key) public returns (bool) ; function getAllKeyType() public view returns (bytes[] memory keyList, bytes[] memory valList, uint retNum); function getNonceFromAccount(address account) constant returns (uint256); function updateNonceFromAccount(address account) internal returns (uint256); function checkNonce(bytes args, bytes32 message, address account) returns (bool); function checkAccount(address account) public view returns (bool); function getInnerAccountAndStatus(address account) public view returns(address,bool); }
用于调用方鉴权, callee is externalAccount用于调用方鉴权, callee is UserAccount.getData()管理方管理key权限
{ function getAccountManager() public returns (address) ; function getAuthManager() public returns (address); function check(address caller, address callee, bytes key) public view returns (bool); function checkWithSign(address callee, bytes key, bytes args, bytes32[4] sign) public view returns (address, bool); function check2(address caller, address org, address callee, bytes key) public view returns (bool) ; function check2WithSign(address org, address callee, bytes key, bytes args, bytes32[4] sign) public view returns (address, bool); function addKeyType(bytes key, bytes value) public returns (bool) ; function removeKeyType(bytes key) public returns (bool) ; function getAllKeyType() public view returns (bytes[] memory keyList, bytes[] memory valList, uint retNum); function getNonceFromAccount(address account) constant returns (uint256); function updateNonceFromAccount(address account) internal returns (uint256); function checkNonce(bytes args, bytes32 message, address account) returns (bool); function checkAccount(address account) public view returns (bool); function getInnerAccountAndStatus(address account) public view returns(address,bool); }
2,543,375
pragma solidity ^0.6.0; // import ownable import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; // import safemath import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol"; contract MunicipalityWasteTaxes is Ownable { // use safemath for uints and integers using SafeMath for uint; using SafeMath for int; // declare variables that will be stored in the blockchain // declare the initial deposit the every citizen will have to payable // for now we set it to approximately to 1/10 ETH ~ 50 € uint deposit = 1 * 10 ** 17 wei; // keep track of the total amount of taxes paid by all citizens // this is not necessary, this information can be accessed using this.balance // uint totalTaxesPaidByCitizens; // declare a mapping that contains many instances of Citizen as a key we need to use something that is specific // to the singular citizen so we can use either the citizenAddress or the fiscalCode (start with citizenAddress) // and see it everything works // this mapping will be called citizens mapping(address => Citizen) citizens; // create a struct where to store data regarding the individual citizens struct Citizen { address citizenAddress; // the ethereum address of the citizen, uniquely identifies a citizen string fiscalCode; // this variable can also uniquely identify each citizen // maybe its better to use bytes32 data type for this variable. bool paidDeposit; // we can add a check to make sure the citizen paid the deposit during the current year int taxesDue; // the amount of taxes the citizen needs to pay to the Municipality // since each citizen pays an initial deposit this number can also be negative uint totalRecyclableWaste; // keep track of the recycable waste produced the particular citizen uint totalNonRecyclableWaste; // keep track of the unrecycable waste produced the particular citizen } //modifiers to limit function calls [address(0) is the default value of the mapping, by checking like below, we see if the account already exists] modifier isntCitizenYet(address _address){require(citizens[_address].citizenAddress == address(0)); _;} //cannot create 2 accounts modifier isCitizenCanPay(address _address){require(citizens[_address].citizenAddress != address(0) && citizens[_address].paidDeposit == false); _;} //can pay only if citizen and not already paid // create a function to instantiate citizens and add them to the citizens mapping // it will be external so that it can be called from outside this contract // WARNING: make sure each address can only call this function once function addCitizen(string calldata _fiscalCode) external isntCitizenYet(msg.sender){ // create an instance of Citizen // pass the variables explicitely Citizen memory citizen = Citizen({ citizenAddress: msg.sender, // the address calling this function will be saved as the citizenAddress fiscalCode: _fiscalCode, // set the fiscalCode to the one provided by the citizen paidDeposit: false, // initially set the paidDeposit variable to false taxesDue: 0, // initially set taxesDue to 0 totalRecyclableWaste: 0, totalNonRecyclableWaste: 0 }); // add the instance of Citizen we just created to the mapping containing all the instances of citizens that is saved // on the blockchain. // as the key of the mapping we use the citizenAddress variable of the specific citizen and // the value associated with it is the instance itself of the Citizen struct we just created citizens[citizen.citizenAddress] = citizen; } // create a function that can be called by individual citizen in order to pay the initial deposit. // to do so, it will need to be external and payable // the amount will be sent to this contract that is owned by the municipality // {potentially expand it so that one citizen can pay the deposit of another citizen} function payDeposit() external payable isCitizenCanPay(msg.sender){ // make sure that the amount sent using this function is at least equal to the deposit required (1/10 ETH) // otherwise revert the transaction // the value sent can be accessed using msg.value if(msg.value >= deposit){ // change the paidDeposit variable of the citizen who paid the deposit to true citizens[msg.sender].paidDeposit = true; } else { // revert the transaction revert(); } } // create a function that modify the totalRecyclableWaste associate with a citizen // since totalRecyclableWaste directly affect the taxes that a citizen will pay, // only the owner of this contract (the municipality) should be able to call it // to achieve this we can use the onlyOwner modifier present in Ownable function _addRecyclableWaste () private onlyOwner { } // create a function that returns the total amount of money sent to this contract by a citizen // since it does not modify the data it will be a view function function getTotalTaxesPaid() external view returns(uint) { return address(this).balance; } // create a function to check the balance of taxes due by a citizen so far // since it does not modify any data it will be a view function function getTaxesDue() external view returns(int) { // we assume that the address calling this function is the oen of the citizen itself return citizens[msg.sender].taxesDue; } // create some functions to access the variables inside the struct of a citizen // create functions to check if you paid the deposit function didIPayDeposit() external view returns(bool) { return citizens[msg.sender].paidDeposit; } // create a function to check the amount of recyclabe waste you produced so far function getAmountRecyclableWaste() external view returns (uint) { return citizens[msg.sender].totalRecyclableWaste; } // create a function to check the amount of non-recyclabe waste you produced so far function getAmountNonRecyclableWaste() external view returns (uint) { return citizens[msg.sender].totalNonRecyclableWaste; } // get the fiscal code // function getFiscalCode() external view returns(string) { // return citizens[msg.sender].fiscalCode; // } } // create a function that can be executed only by the owner of the contract (the unicipality itself in our case) // at the end of the year that sets the paidDeposit field for every citizen to false
create a function that can be called by individual citizen in order to pay the initial deposit. to do so, it will need to be external and payable the amount will be sent to this contract that is owned by the municipality {potentially expand it so that one citizen can pay the deposit of another citizen} make sure that the amount sent using this function is at least equal to the deposit required (1/10 ETH) otherwise revert the transaction the value sent can be accessed using msg.value change the paidDeposit variable of the citizen who paid the deposit to true revert the transaction
function payDeposit() external payable isCitizenCanPay(msg.sender){ if(msg.value >= deposit){ citizens[msg.sender].paidDeposit = true; revert(); } }
12,979,057
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./IERC721LibBeforeTokenTransferHook.sol"; /* Functionality used to whitelist OpenSea trading address, if desired */ contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, the Enumerable extension, and Pausable. * * Closely based on and mirrors the excellent https://openzeppelin.com/contracts/. */ library ERC721Lib { using Address for address; using Strings for uint256; /** * @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 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); struct ERC721Storage { // Token name string _name; // Token symbol string _symbol; // Mapping from token ID to owner address mapping (uint256 => address) _owners; // Mapping owner address to token count mapping (address => uint256) _balances; // Mapping from token ID to approved address mapping (uint256 => address) _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) _operatorApprovals; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) _allTokensIndex; // Base URI string _baseURI; // True if token transfers are paused bool _paused; // Hook function that can be called before token is transferred, along with a pointer to its storage struct IERC721LibBeforeTokenTransferHook _beforeTokenTransferHookInterface; bytes32 _beforeTokenTransferHookStorageSlot; address proxyRegistryAddress; } function init(ERC721Storage storage s, string memory _name, string memory _symbol) external { s._name = _name; s._symbol = _symbol; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) external pure returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId; } // // Start of ERC721 functions // /** * @dev See {IERC721-balanceOf}. */ function _balanceOf(ERC721Storage storage s, address owner) internal view returns (uint256) { require(owner != address(0), "Balance query for address zero"); return s._balances[owner]; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(ERC721Storage storage s, address owner) external view returns (uint256) { return _balanceOf(s, owner); } /** * @dev See {IERC721-ownerOf}. */ function _ownerOf(ERC721Storage storage s, uint256 tokenId) internal view returns (address) { address owner = s._owners[tokenId]; require(owner != address(0), "Owner query for nonexist. token"); return owner; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(ERC721Storage storage s, uint256 tokenId) external view returns (address) { return _ownerOf(s, tokenId); } /** * @dev See {IERC721Metadata-name}. */ function name(ERC721Storage storage s) external view returns (string memory) { return s._name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol(ERC721Storage storage s) external view returns (string memory) { return s._symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(ERC721Storage storage s, uint256 tokenId) external view returns (string memory) { require(_exists(s, tokenId), "URI query for nonexistent token"); return bytes(s._baseURI).length > 0 ? string(abi.encodePacked(s._baseURI, tokenId.toString())) : ""; } /** * @dev Set base URI */ function setBaseURI(ERC721Storage storage s, string memory baseTokenURI) external { s._baseURI = baseTokenURI; } /** * @dev See {IERC721-approve}. */ function approve(ERC721Storage storage s, address to, uint256 tokenId) external { address owner = _ownerOf(s, tokenId); require(to != owner, "Approval to current owner"); require(msg.sender == owner || _isApprovedForAll(s, owner, msg.sender), "Not owner nor approved for all" ); _approve(s, to, tokenId); } /** * @dev Approve independently of who's the owner * * Obviously expose with care... */ function overrideApprove(ERC721Storage storage s, address to, uint256 tokenId) external { _approve(s, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function _getApproved(ERC721Storage storage s, uint256 tokenId) internal view returns (address) { require(_exists(s, tokenId), "Approved query nonexist. token"); return s._tokenApprovals[tokenId]; } /** * @dev See {IERC721-getApproved}. */ function getApproved(ERC721Storage storage s, uint256 tokenId) external view returns (address) { return _getApproved(s, tokenId); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(ERC721Storage storage s, address operator, bool approved) external { require(operator != msg.sender, "Attempted approve to caller"); s._operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function _isApprovedForAll(ERC721Storage storage s, address owner, address operator) internal view returns (bool) { // Whitelist OpenSea proxy contract for easy trading - if we have a valid proxy registry address on file if (s.proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(s.proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return s._operatorApprovals[owner][operator]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(ERC721Storage storage s, address owner, address operator) external view returns (bool) { return _isApprovedForAll(s, owner, operator); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved"); _transfer(s, from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external { _safeTransferFrom(s, from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function _safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal { require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved"); _safeTransfer(s, from, to, tokenId, _data); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external { _safeTransferFrom(s, 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(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal { _transfer(s, from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "Transfer to non ERC721Receiver"); } /** * @dev directSafeTransfer * * CAREFUL, this does not verify the previous ownership - only use if ownership/eligibility has been asserted by other means */ function directSafeTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external { _safeTransfer(s, from, to, tokenId, _data); } /** * @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(ERC721Storage storage s, uint256 tokenId) internal view returns (bool) { return s._owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(ERC721Storage storage s, address spender, uint256 tokenId) internal view returns (bool) { require(_exists(s, tokenId), "Operator query nonexist. token"); address owner = _ownerOf(s, tokenId); return (spender == owner || _getApproved(s, tokenId) == spender || _isApprovedForAll(s, owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(ERC721Storage storage s, address to, uint256 tokenId) internal { _safeMint(s, 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(ERC721Storage storage s, address to, uint256 tokenId, bytes memory _data) internal { _unsafeMint(s, to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "Transfer to non ERC721Receiver"); } /** * @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 _unsafeMint(ERC721Storage storage s, address to, uint256 tokenId) internal { require(to != address(0), "Mint to the zero address"); require(!_exists(s, tokenId), "Token already minted"); _beforeTokenTransfer(s, address(0), to, tokenId); s._balances[to] += 1; s._owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(ERC721Storage storage s, uint256 tokenId) internal { address owner = _ownerOf(s, tokenId); _beforeTokenTransfer(s, owner, address(0), tokenId); // Clear approvals _approve(s, address(0), tokenId); s._balances[owner] -= 1; delete s._owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(ERC721Storage storage s, address from, address to, uint256 tokenId) internal { require(_ownerOf(s, tokenId) == from, "TransferFrom not owner/approved"); require(to != address(0), "Transfer to the zero address"); _beforeTokenTransfer(s, from, to, tokenId); // Clear approvals from the previous owner _approve(s, address(0), tokenId); s._balances[from] -= 1; s._balances[to] += 1; s._owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(ERC721Storage storage s, address to, uint256 tokenId) internal { s._tokenApprovals[tokenId] = to; emit Approval(_ownerOf(s, tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("Transfer to non ERC721Receiver"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // // Start of functions from ERC721Enumerable // /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(ERC721Storage storage s, address owner, uint256 index) external view returns (uint256) { require(index < _balanceOf(s, owner), "Owner index out of bounds"); return s._ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function _totalSupply(ERC721Storage storage s) internal view returns (uint256) { return s._allTokens.length; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply(ERC721Storage storage s) external view returns (uint256) { return s._allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(ERC721Storage storage s, uint256 index) external view returns (uint256) { require(index < _totalSupply(s), "Global index out of bounds"); return s._allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId) internal { if(address(s._beforeTokenTransferHookInterface) != address(0)) { // We have a hook that we need to delegate call (bool success, ) = address(s._beforeTokenTransferHookInterface).delegatecall( abi.encodeWithSelector(s._beforeTokenTransferHookInterface._beforeTokenTransferHook.selector, s._beforeTokenTransferHookStorageSlot, from, to, tokenId) ); if(!success) { // Bubble up the revert message assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } } require(!_paused(s), "No token transfer while paused"); if (from == address(0)) { _addTokenToAllTokensEnumeration(s, tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(s, from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(s, tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(s, to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(ERC721Storage storage s, address to, uint256 tokenId) private { uint256 length = _balanceOf(s, to); s._ownedTokens[to][length] = tokenId; s._ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(ERC721Storage storage s, uint256 tokenId) private { s._allTokensIndex[tokenId] = s._allTokens.length; s._allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(ERC721Storage storage s, address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _balanceOf(s, from) - 1; uint256 tokenIndex = s._ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = s._ownedTokens[from][lastTokenIndex]; s._ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token s._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete s._ownedTokensIndex[tokenId]; delete s._ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(ERC721Storage storage s, uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = s._allTokens.length - 1; uint256 tokenIndex = s._allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = s._allTokens[lastTokenIndex]; s._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token s._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete s._allTokensIndex[tokenId]; s._allTokens.pop(); } // // Start of functions from Pausable // /** * @dev Returns true if the contract is paused, and false otherwise. */ function _paused(ERC721Storage storage s) internal view returns (bool) { return s._paused; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused(ERC721Storage storage s) external view returns (bool) { return s._paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused(ERC721Storage storage s) { require(!_paused(s), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused(ERC721Storage storage s) { require(_paused(s), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause(ERC721Storage storage s) external whenNotPaused(s) { s._paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause(ERC721Storage storage s) external whenPaused(s) { s._paused = false; emit Unpaused(msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Lib.sol"; /** * @dev Interface that can be used to hook additional beforeTokenTransfer functions into ERC721Lib */ interface IERC721LibBeforeTokenTransferHook { /** * @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 _beforeTokenTransferHook(bytes32 storagePosition, address from, address to, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the call return bool whether the call correctly returned the expected magic value/ solhint-disable-next-line no-inline-assembly
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert("Transfer to non ERC721Receiver"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } }
6,935,794
./full_match/84531/0x5a9195d9b4B3a09945545F942B41080FDeCe4F7a/sources/contracts/coretime.sol
2x of remaining days pricePerDay
function getCurrentPriceETH(uint256 _tokenId) public view returns (uint256) { TokenInfo storage token = tokenInfo[_tokenId]; if ( totalSupply() == 0 || token.expirationTimestamp == 0 || block.timestamp > token.expirationTimestamp ) { return priceFloorEth; } return (token.expirationTimestamp - block.timestamp) .mul(2) .mul(token.pricePerDay) .div(1 days); }
11,512,762
pragma solidity ^0.4.24; /** * @title -FoMo-3D v0.7.1 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ .--,-``-. *========,---,.======================____==========================/ / '.=======,---,====* * ,' .' | ,' , `. / ../ ; .' .' `\ * ,---.' | ,---. ,-+-,.' _ | ,---. \ ``\ .`- ' ,---.' \ * | | .' ' ,'\ ,-+-. ; , || ' ,'\ ,---,. \___\/ \ : | | .`\ | * : : : / / | ,--.'|' | || / / | ,' .' | \ : | : : | ' | * : | |-, . ; ,. : | | ,', | |, . ; ,. : ,---.' | / / / | ' ' ; : * | : ;/| ' | |: : | | / | |--' ' | |: : | | .' \ \ \ ' | ; . | * | | .' ' | .; : | : | | , ' | .; : : |.' ___ / : | | | : | ' * ' : ' | : | | : | |/ | : | `---' / /\ / : ' : | / ; * | | | \ \ / | | |`-' \ \ / / ,,/ ',- . | | '` ,/ * | : \ `----' | ;/ `----' \ ''\ ; ; : .' *====| | ,'=============='---'==========(long version)===========\ \ .'===| ,.'======* * `----' `--`-,,-' '---' * ╔═╗┌─┐┌─┐┬┌─┐┬┌─┐┬ ┌─────────────────────────┐ ╦ ╦┌─┐┌┐ ╔═╗┬┌┬┐┌─┐ * ║ ║├┤ ├┤ ││ │├─┤│ │ https://exitscam.me │ ║║║├┤ ├┴┐╚═╗│ │ ├┤ * ╚═╝└ └ ┴└─┘┴┴ ┴┴─┘ └─┬─────────────────────┬─┘ ╚╩╝└─┘└─┘╚═╝┴ ┴ └─┘ * ┌────────────────────────────────┘ └──────────────────────────────┐ * │╔═╗┌─┐┬ ┬┌┬┐┬┌┬┐┬ ┬ ╔╦╗┌─┐┌─┐┬┌─┐┌┐┌ ╦┌┐┌┌┬┐┌─┐┬─┐┌─┐┌─┐┌─┐┌─┐ ╔═╗┌┬┐┌─┐┌─┐┬┌─│ * │╚═╗│ ││ │ │││ │ └┬┘ ═ ║║├┤ └─┐││ ┬│││ ═ ║│││ │ ├┤ ├┬┘├┤ ├─┤│ ├┤ ═ ╚═╗ │ ├─┤│ ├┴┐│ * │╚═╝└─┘┴─┘┴─┴┘┴ ┴ ┴ ═╩╝└─┘└─┘┴└─┘┘└┘ ╩┘└┘ ┴ └─┘┴└─└ ┴ ┴└─┘└─┘ ╚═╝ ┴ ┴ ┴└─┘┴ ┴│ * │ ┌──────────┐ ┌───────┐ ┌─────────┐ ┌────────┐ │ * └────┤ Inventor ├───────────┤ Justo ├────────────┤ Sumpunk ├──────────────┤ Mantso ├──┘ * └──────────┘ └───────┘ └─────────┘ └────────┘ * ┌─────────────────────────────────────────────────────────┐ ╔╦╗┬ ┬┌─┐┌┐┌┬┌─┌─┐ ╔╦╗┌─┐ * │ ChungkueiBlock, Ambius, Aritz Cracker, Cryptoknight, │ ║ ├─┤├─┤│││├┴┐└─┐ ║ │ │ * │ Capex, JogFera, The Shocker, Daok, Randazzz, PumpRabbi, │ ╩ ┴ ┴┴ ┴┘└┘┴ ┴└─┘ ╩ └─┘ * │ Kadaz, Incognito Jo, Lil Stronghands, Ninja Turtle, └───────────────────────────┐ * │ Psaints, Satoshi, Vitalik, Nano 2nd, Bogdanoffs Isaac Newton, Nikola Tesla, │ * │ Le Comte De Saint Germain, Albert Einstein, Socrates, & all the volunteer moderator │ * │ & support staff, content, creators, autonomous agents, and indie devs for P3D. │ * │ Without your help, we wouldn't have the time to code this. │ * └─────────────────────────────────────────────────────────────────────────────────────┘ * * This product is protected under license. Any unauthorized copy, modification, or use without * express written consent from the creators is prohibited. * * WARNING: THIS PRODUCT IS HIGHLY ADDICTIVE. IF YOU HAVE AN ADDICTIVE NATURE. DO NOT PLAY. */ //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents { } contract FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; // otherFoMo3D private otherF3D_; address private otherF3D_; // remove the 害虫 // DiviesInterface constant private Divies = DiviesInterface(0xe7d5f7a1afbfeb44894c1114fb021cab7e0367fd); // 简化社区分红 // JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0x548e2295fc38b69000ff43a730933919b08c2562); PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x4c9382454cb0553aee069d302c3ef2e48b0d7852); // hack 闭源合约 // F3DexternalSettingsInterface constant private extSettings = F3DexternalSettingsInterface(0x85C2d5079DC6C2856116C41f4EDd2E3EBBb63B5C); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "imfomo Long Official"; string constant public symbol = "imfomo"; uint256 private rndExtra_ = 30; // length of the very first ICO uint256 private rndGap_ = 30; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 10 minutes; // round timer starts at this uint256 constant private rndInc_ = 60 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 10 minutes; // max length a round timer can be address constant private reward = 0x0e4AF6199f2b92d6677c44d7722CB60cD46FCef6; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(31,0); //50% to pot, 15% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(38,0); //43% to pot, 15% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(61,0); //20% to pot, 15% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(46,0); //35% to pot, 15% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15,0); //58% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(15,0); //58% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(30,0); //58% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30,0); //58% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(58)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter // 当一轮刚开始时,合约收到的总ETH数小于100且某用户累计充值超过1ETH的时候,将不再能买到keys,你多余钱会直接计入你的收益 // if (round_[_rID].eth < 1000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) // { // uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); // uint256 _refund = _eth.sub(_availableLimit); // plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); // _eth = _availableLimit; // } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; // >= 10 ether if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; // >= 1 && < 10 ether } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; // >= 0.1 && <= 1 ether } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(58)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards // if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) // { // // This ensures Team Just cannot influence the outcome of FoMo3D with // // bank migrations by breaking outgoing transactions. // // Something we would never do. But that's not the point. // // We spent 2000$ in eth re-deploying just to patch this, we hold the // // highest belief that everything we create should be trustless. // // Team JUST, The name you shouldn't have to trust. // _p3d = _p3d.add(_com); // _com = 0; // } _p3d = _p3d.add(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies // Divies.deposit.value(_p3d)(); if (_p3d > 0) reward.send(_p3d); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; uint256 _p3d; // if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) // { // // This ensures Team Just cannot influence the outcome of FoMo3D with // // bank migrations by breaking outgoing transactions. // // Something we would never do. But that's not the point. // // We spent 2000$ in eth re-deploying just to patch this, we hold the // // highest belief that everything we create should be trustless. // // Team JUST, The name you shouldn't have to trust. // _p3d = _com; // _com = 0; // } _p3d = _p3d.add(_com); // pay 1% out to FoMo3D short uint256 _long = _eth / 100; otherF3D_.send(_long); // distribute share to affiliate uint256 _aff; uint256 _aff2; uint256 _affID2 = plyr_[_affID].laff; if (_affID2 != 0 && plyr_[_affID2].name != "") { _aff = _eth.mul(10) / 100; _aff2 = _eth.mul(5) / 100; plyr_[_affID2].aff = _aff2.add(plyr_[_affID2].aff); } else { _aff = _eth.mul(15) / 100; } // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != "") { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); // emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _p3d.add(_aff); } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract // Divies.deposit.value(_p3d)(); reward.send(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(19)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f || msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f || msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f, "only team just can activate" ); // make sure that its been linked. require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } function setOtherFomo(address _otherF3D) public { // only team just can activate require( msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f || msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f || msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f, "only team just can activate" ); // make sure that it HASNT yet been linked. require(address(otherF3D_) == address(0), "silly dev, you already did that"); // set up other fomo3d (fast or long) for pot swap // otherF3D_ = otherFoMo3D(_otherF3D); otherF3D_ = _otherF3D; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface otherFoMo3D { function potSwap() external payable; } interface F3DexternalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } interface DiviesInterface { function deposit() external payable; } interface JIincForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
ends the round. manages paying out winner/splitting up pot/ setup local rID grab our winning player and team id's grab our pot amount calculate our winner share, community rewards, gen share, p3d share, and amount reserved for next pot calculate ppt for round mask
function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _rID = rID_; uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; uint256 _pot = round_[_rID].pot; uint256 _win = (_pot.mul(58)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } _p3d = _p3d.add(_com); reward.send(_p3d); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); }
1,181,144
pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/utils/EnumerableMap.sol pragma solidity ^0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) {// Equivalent to !contains(map, key) map._entries.push(MapEntry({_key : key, _value : value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) {// Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/utils/EnumerableSet.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) {// Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/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; // solhint-disable-next-line no-inline-assembly assembly {size := extcodesize(account)} return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success,) = recipient.call{value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value : value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(type(IERC165).interfaceId); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/introspection/IERC165.sol // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // 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; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(type(IERC721).interfaceId); _registerInterface(type(IERC721Metadata).interfaceId); _registerInterface(type(IERC721Enumerable).interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _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(), ".json")); } /** * @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()) { 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("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } 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 {} } // File: http://github.com/OpenZeppelin/openzeppelin-contracts/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { 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; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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; } } } pragma solidity ^0.8.0; // SPDX-License-Identifier: UNLICENSED contract CodeofWonder is ERC721, Ownable { using SafeMath for uint256; using Strings for uint256; uint public constant MAX_TOKENS = 1000; mapping(uint256 => uint256) public creationDates; mapping(uint256 => address) public creators; string public METADATA_PROVENANCE_HASH = ""; string public GENERATOR_ADDRESS = "MYURL/script.php?number="; constructor() ERC721("Code of Wonder", "COW") { setBaseURI("garbage uri"); _safeMint(msg.sender, 0); creationDates[0] = block.number; creators[0] = msg.sender; } function tokensOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function mintToken(uint256 maxTOKENS) public onlyOwner { require(totalSupply() < MAX_TOKENS, "Sale has already ended"); require(maxTOKENS > 0 && maxTOKENS <= 10, "You can claim minimum 1, maximum 10 tokens"); require(totalSupply().add(maxTOKENS) <= MAX_TOKENS, "Exceeds MAX_TOKENS"); for (uint i = 0; i < maxTOKENS; i++) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); creationDates[mintIndex] = block.number; creators[mintIndex] = msg.sender; } } function setProvenanceHash(string memory _hash) public onlyOwner { METADATA_PROVENANCE_HASH = _hash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function tokenHash(uint256 tokenId) public view returns (bytes32){ require(_exists(tokenId), "DOES NOT EXIST"); return bytes32(keccak256(abi.encodePacked(address(this), creationDates[tokenId], creators[tokenId], tokenId))); } function generatorAddress(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "DOES NOT EXIST"); return string(abi.encodePacked(GENERATOR_ADDRESS, tokenId.toString())); } }
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)))); }
16,027
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
Reads the uint96 at `cdPtr` in calldata.
function readUint96( CalldataPointer cdPtr ) internal pure returns (uint96 value) { assembly { value := calldataload(cdPtr) } }
3,218,276
./full_match/1/0x864a1CBB53b9Dea3691a6974B456088C2771DcAd/sources/browser/Bar.sol
Internal function that buys back BOOGIE with the amount of ETH specified
function _buyBoogie(uint256 _amount) internal returns (uint256 boogieBought) { uint256 ethBalance = address(this).balance; if (_amount > ethBalance) _amount = ethBalance; if (_amount > 0) { uint256 deadline = block.timestamp + 5 minutes; address[] memory boogiePath = new address[](2); boogiePath[0] = address(weth); boogiePath[1] = address(boogie); boogieBought = amounts[1]; } if (boogieBought > 0) emit BoogieBuyback(msg.sender, _amount, boogieBought); }
4,927,192
// SPDX-License-Identifier: Apache-2.0 /****************************************************************************** * Copyright 2020 IEXEC BLOCKCHAIN TECH * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ******************************************************************************/ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IexecERC20Core.sol"; import "./SignatureVerifier.sol"; import "../DelegateBase.sol"; import "../interfaces/IexecEscrowTokenSwap.sol"; import "../interfaces/IexecPoco1.sol"; contract IexecEscrowTokenSwapDelegate is IexecEscrowTokenSwap, DelegateBase, IexecERC20Core, SignatureVerifier { using SafeMathExtended for uint256; using IexecLibOrders_v5 for IexecLibOrders_v5.AppOrder; using IexecLibOrders_v5 for IexecLibOrders_v5.DatasetOrder; using IexecLibOrders_v5 for IexecLibOrders_v5.WorkerpoolOrder; using IexecLibOrders_v5 for IexecLibOrders_v5.RequestOrder; IUniswapV2Router02 internal constant router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); /*************************************************************************** * Accessor * ***************************************************************************/ function UniswapV2Router() external view override returns (IUniswapV2Router02) { return router; } /*************************************************************************** * Uniswap path - Internal * ***************************************************************************/ function _eth2token() internal view returns (address[] memory) { address[] memory path = new address[](2); path[0] = router.WETH(); path[1] = address(m_baseToken); return path; } function _token2eth() internal view returns (address[] memory) { address[] memory path = new address[](2); path[0] = address(m_baseToken); path[1] = router.WETH(); return path; } /*************************************************************************** * Prediction methods - Public * ***************************************************************************/ function estimateDepositEthSent (uint256 eth ) external view override returns (uint256 token) { return router.getAmountsOut(eth, _eth2token())[1]; } function estimateDepositTokenWanted(uint256 token) external view override returns (uint256 eth ) { return router.getAmountsIn (token, _eth2token())[0]; } function estimateWithdrawTokenSent (uint256 token) external view override returns (uint256 eth ) { return router.getAmountsOut(token, _token2eth())[1]; } function estimateWithdrawEthWanted (uint256 eth ) external view override returns (uint256 token) { return router.getAmountsIn (eth, _token2eth())[0]; } /*************************************************************************** * Swapping methods - Public * ***************************************************************************/ receive() external override payable { address sender = _msgSender(); if (sender != address(router)) { _deposit(sender, msg.value, 0); } } fallback() external override payable { revert('fallback-disabled'); } function depositEth ( ) external override payable { _deposit(_msgSender(), msg.value, 0 ); } function depositEthFor ( address target) external override payable { _deposit(target, msg.value, 0 ); } function safeDepositEth ( uint256 minimum ) external override payable { _deposit(_msgSender(), msg.value, minimum); } function safeDepositEthFor( uint256 minimum, address target) external override payable { _deposit(target, msg.value, minimum); } function requestToken (uint256 amount ) external override payable { _request(_msgSender(), msg.value, amount ); } function requestTokenFor (uint256 amount, address target) external override payable { _request(target, msg.value, amount ); } function withdrawEth (uint256 amount ) external override { _withdraw(_msgSender(), amount, 0 ); } function withdrawEthTo (uint256 amount, address target) external override { _withdraw(target, amount, 0 ); } function safeWithdrawEth (uint256 amount, uint256 minimum ) external override { _withdraw(_msgSender(), amount, minimum); } function safeWithdrawEthTo(uint256 amount, uint256 minimum, address target) external override { _withdraw(target, amount, minimum); } /*************************************************************************** * Swapping methods - Internal * ***************************************************************************/ function _deposit(address target, uint256 value, uint256 minimum) internal { uint256[] memory amounts = router.swapExactETHForTokens{value: value}(minimum, _eth2token(), address(this), now+1); _mint(target, amounts[1]); } function _request(address target, uint256 value, uint256 amount) internal { uint256[] memory amounts = router.swapETHForExactTokens{value: value}(amount, _eth2token(), address(this), now+1); _mint(target, amounts[1]); // Refund remaining ETH (bool success, ) = _msgSender().call{value: value.sub(amounts[0])}(''); require(success, 'native-transfer-failed'); } function _withdraw(address target, uint256 amount, uint256 minimum) internal { m_baseToken.approve(address(router), amount); uint256[] memory amounts = router.swapExactTokensForETH(amount, minimum, _token2eth(), target, now+1); _burn(_msgSender(), amounts[0]); } /*************************************************************************** * Extra public methods * ***************************************************************************/ function matchOrdersWithEth( IexecLibOrders_v5.AppOrder memory _apporder, IexecLibOrders_v5.DatasetOrder memory _datasetorder, IexecLibOrders_v5.WorkerpoolOrder memory _workerpoolorder, IexecLibOrders_v5.RequestOrder memory _requestorder) public payable override returns (bytes32) { uint256 volume; volume = _apporder.volume.sub(m_consumed[keccak256(_toEthTypedStruct( _apporder.hash(), EIP712DOMAIN_SEPARATOR))]); if (_datasetorder.dataset != address(0)) volume = volume.min( _datasetorder.volume.sub(m_consumed[keccak256(_toEthTypedStruct( _datasetorder.hash(), EIP712DOMAIN_SEPARATOR))])); volume = volume.min(_workerpoolorder.volume.sub(m_consumed[keccak256(_toEthTypedStruct(_workerpoolorder.hash(), EIP712DOMAIN_SEPARATOR))])); volume = volume.min( _requestorder.volume.sub(m_consumed[keccak256(_toEthTypedStruct( _requestorder.hash(), EIP712DOMAIN_SEPARATOR))])); _request( _requestorder.requester, msg.value, _apporder.appprice .add(_datasetorder.dataset != address(0) ? _datasetorder.datasetprice : 0) .add(_workerpoolorder.workerpoolprice) .mul(volume) ); return IexecPoco1(address(this)).matchOrders(_apporder, _datasetorder, _workerpoolorder, _requestorder); } }
Prediction methods - Public /
function estimateDepositEthSent (uint256 eth ) external view override returns (uint256 token) { return router.getAmountsOut(eth, _eth2token())[1]; }
15,845,470
pragma solidity 0.4.18; /** * Math operations with safety checks */ contract BaseSafeMath { /* standard uint256 functions */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert( b > 0 ); uint256 c = a / b; return c; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } /* uint128 functions */ function madd(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; assert(c >= a); return c; } function msub(uint128 a, uint128 b) internal pure returns (uint128) { assert(b <= a); return a - b; } function mmul(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a * b; assert(a == 0 || c / a == b); return c; } function mdiv(uint128 a, uint128 b) internal pure returns (uint128) { assert( b > 0 ); uint128 c = a / b; return c; } function mmin(uint128 x, uint128 y) internal pure returns (uint128 z) { return x <= y ? x : y; } function mmax(uint128 x, uint128 y) internal pure returns (uint128 z) { return x >= y ? x : y; } /* uint64 functions */ function miadd(uint64 a, uint64 b) internal pure returns (uint64) { uint64 c = a + b; assert(c >= a); return c; } function misub(uint64 a, uint64 b) internal pure returns (uint64) { assert(b <= a); return a - b; } function mimul(uint64 a, uint64 b) internal pure returns (uint64) { uint64 c = a * b; assert(a == 0 || c / a == b); return c; } function midiv(uint64 a, uint64 b) internal pure returns (uint64) { assert( b > 0 ); uint64 c = a / b; return c; } function mimin(uint64 x, uint64 y) internal pure returns (uint64 z) { return x <= y ? x : y; } function mimax(uint64 x, uint64 y) internal pure returns (uint64 z) { return x >= y ? x : y; } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 contract BaseERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowed; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal; /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success); /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success); } /** * @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 publishOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { publishOwner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == publishOwner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(publishOwner, newOwner); publishOwner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @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 LightCoinToken is BaseERC20, BaseSafeMath, Pausable { //The solidity created time address public owner; address public lockOwner; uint256 public lockAmount ; uint256 public startTime ; function LightCoinToken() public { owner = 0x55ae8974743DB03761356D703A9cfc0F24045ebb; lockOwner = 0x07d4C8CC52BB7c4AB46A1A65DCEEdC1ab29aBDd6; startTime = 1515686400; name = "Lightcoin"; symbol = "Light"; decimals = 8; ///totalSupply = 21000000000000000000; totalSupply = 2.1e19; balanceOf[owner] = totalSupply * 90 /100; lockAmount = totalSupply * 10 / 100 ; Transfer(address(0), owner, balanceOf[owner]); } /// @param _owner The address from which the balance will be retrieved /// @return The balance function getBalanceOf(address _owner) public constant returns (uint256 balance) { return balanceOf[_owner]; } function _transfer(address _from, address _to, uint256 _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Save this for an assertion in the future uint previousBalances = add(balanceOf[_from], balanceOf[_to]); // Subtract from the sender balanceOf[_from] = sub(balanceOf[_from], _value); // Add the same to the recipient balanceOf[_to] = add(balanceOf[_to], _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(add(balanceOf[_from], balanceOf[_to]) == previousBalances); Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool success) { // Check allowance allowed[_from][msg.sender] = sub(allowed[_from][msg.sender], _value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function releaseToken() public{ uint256 releaseBegin = add(startTime, 2 * 365 * 86400); require(now >= releaseBegin ); uint256 interval = sub(now, releaseBegin); uint256 i = div(interval, (0.5 * 365 * 86400)); if (i > 3) { i = 3; } uint256 releasevalue = div(totalSupply, 40); uint256 remainInterval = sub(3, i); require(lockAmount > mul(remainInterval, releasevalue)); lockAmount = sub(lockAmount, releasevalue); balanceOf[lockOwner] = add( balanceOf[lockOwner], releasevalue); Transfer(address(0), lockOwner, releasevalue); } function () public payable{ revert(); } }
_owner The address of the account owning tokens _spender The address of the account able to transfer the tokens return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
7,947,539
./full_match/5/0x88313c8AbF9c3e2B67D8a8C90203184F0CF86b77/sources/contracts/ThirdwebRentableERC721A.sol
We make it so that anyone can mint tokens that have already been lazy minted./ check permissions check to make sure there are lazy minted tokens to be minted
function mintTo(address _to, string memory _tokenURI) public virtual { require(hasRole(MINTER_ROLE, msg.sender),"must have minter role to mint"); uint256 quantity = 1; require( _nextTokenId() + quantity <= nextTokenIdToLazyMint, "Not enough lazy minted tokens." ); fullURI[nextTokenIdToLazyMint] = _tokenURI; _safeMint(_to, quantity, ""); }
11,623,282
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _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; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { 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 { } } // File: contracts/SandwichToken.sol pragma solidity 0.6.12; // SandwichToken with Governance. contract SandwichToken is ERC20("SandwichToken", "SWH"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SANDWICH::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SANDWICH::delegateBySig: invalid nonce"); require(now <= expiry, "SANDWICH::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SANDWICH::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SWHs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SANDWICH::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/MasterChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SandwichSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // SandwichSwap must mint EXACTLY the same amount of SandwichSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Sandwich. He can make Sandwich and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SANDWICH is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SWHs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSandwichPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSandwichPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SWHs to distribute per block. uint256 lastRewardBlock; // Last block number that SWHs distribution occurs. uint256 accSandwichPerShare; // Accumulated SWHs per share, times 1e12. See below. } // The SANDWICH TOKEN! SandwichToken public sandwich; // Dev address. address public devaddr; // Block number when bonus SWH period ends. uint256 public bonusEndBlock; // SANDWICH tokens created per block. uint256 public swhPerBlock; // Bonus muliplier for early sandwich makers. uint256 public constant BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SWH mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SandwichOwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor( SandwichToken _sandwich, address _devaddr, uint256 _swhPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sandwich = _sandwich; devaddr = _devaddr; swhPerBlock = _swhPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSandwichPerShare: 0 })); } // Update the given pool's SANDWICH allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint,uint256 _lastRewardBlock, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lastRewardBlock = _lastRewardBlock; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return 0; } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER); } } // View function to see pending SWHs on frontend. function pendingSandwich(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSandwichPerShare = pool.accSandwichPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0 && pool.lastRewardBlock <= bonusEndBlock) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 swhReward = multiplier.mul(swhPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSandwichPerShare = accSandwichPerShare.add(swhReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSandwichPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 swhReward = multiplier.mul(swhPerBlock).mul(pool.allocPoint).div(totalAllocPoint); //sandwich.mint(devaddr, swhReward.div(10));//delete devaddr reward sandwich.mint(address(this), swhReward); pool.accSandwichPerShare = pool.accSandwichPerShare.add(swhReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SANDWICH allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSandwichPerShare).div(1e12).sub(user.rewardDebt); safeSwhTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSandwichPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSandwichPerShare).div(1e12).sub(user.rewardDebt); safeSwhTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSandwichPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sandwich transfer function, just in case if rounding error causes pool to not have enough SWHs. function safeSwhTransfer(address _to, uint256 _amount) internal { uint256 sandwichBal = sandwich.balanceOf(address(this)); if (_amount > sandwichBal) { sandwich.transfer(_to, sandwichBal); } else { sandwich.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferTokenOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); sandwich.transferOwnership(newOwner); emit SandwichOwnershipTransferred(address(this),newOwner); } /** * @dev update th reward per block. * Can only be called by the current owner. */ function updateSwhPerBlock(uint256 _swhPerBlock) public virtual onlyOwner { swhPerBlock = _swhPerBlock; } /** * @dev reset mint period. * Can only be called by the current owner. */ function updateMintPeriod(uint256 _startBlock,uint256 _bonusEndBlock) public virtual onlyOwner { startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; } }
decrease old representative increase new representative
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } }
17,066
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title RestrictedToken * @dev An ERC20 token that can only be transferred to whitelisted accounts. */ contract RestrictedToken is Ownable, ERC20, ERC20Detailed { // Approved recipients of the token mapping (address => bool) _whitelist; // events event Whitelisted(address whitelisted); event Removed(address removed); /** * @dev Initialize a restricted token. `msg.sender` gets all the tokens. * @param name The token name * @param symbol The token's symbol * @param decimals The number of decimals * @param initialSupply The supply of tokens * @param initialWhitelist The initial set of accounts approved to receive token transfers. */ constructor( string memory name, string memory symbol, uint8 decimals, uint initialSupply, address[] memory initialWhitelist ) public ERC20Detailed(name, symbol, decimals) { // Owner gets the initial supply _mint(msg.sender, initialSupply); // Whitelist the initial set of accounts. Duplicate addresses are a noop. for (uint i = 0; i < initialWhitelist.length; i++) { address account = initialWhitelist[i]; addToWhitelist(account); } } // Whitelist functions /** * @dev Check if an account is whitelisted for transfers * @param account The address to check * @return true if the account is whitelisted */ function isWhitelisted(address account) public view returns (bool) { return _whitelist[account]; } /** * @dev Add an account to the whitelist for transfers. Revert on zero address. * @param account The address to add */ function addToWhitelist(address account) public onlyOwner { require(account != address(0), "Invalid account address"); require(isWhitelisted(account) == false, "Account is already whitelisted"); _whitelist[account] = true; emit Whitelisted(account); } /** * @dev Remove an account from the whitelist for transfers. Revert on zero address. * @param account The address to remove */ function removeFromWhitelist(address account) public onlyOwner { require(account != address(0), "Invalid account address"); require(isWhitelisted(account) == true, "Cannot remove a non-whitelisted account"); _whitelist[account] = false; emit Removed(account); } // Overrides /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. * @return true if the transfer was successful */ function transfer(address to, uint256 value) public returns (bool) { require(isWhitelisted(to), "Token cannot be be transferred to non-whitelisted address"); return super.transfer(to, value); } /** * @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 * @return true if the transfer was successful */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(isWhitelisted(to), "Token cannot be be transferred to non-whitelisted address"); return super.transferFrom(from, to, value); } }
Whitelist functions Check if an account is whitelisted for transfers account The address to check return true if the account is whitelisted/
function isWhitelisted(address account) public view returns (bool) { return _whitelist[account]; }
7,276,699
./full_match/8453/0x33d34437238A91c18242715a523c2F0A4d74C904/sources/contracts/CorePair.sol
this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) { uint balance0 = IERC20(_token0).balanceOf(address(this)); uint balance1 = IERC20(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); require(amount0 > 0 && amount1 > 0, 'CorePair: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1); emit Burn(msg.sender, amount0, amount1, to); }
11,558,416
./full_match/4/0x171126e37E7C3d8E92325388C97899aD43C13768/sources/browser/Untitled1.sol
.div(15) - 1 eth block is mine every ~15 sec, rewardRatePerBlock scaled by 1e18, and 100 is %
function calcReward(uint amount) public view returns (uint) { uint duration = withdrawStart.sub(stakingEnd); uint rewardAmount = amount.mul(rewardRatePerBlock).mul(duration).div(15).div(1e18).div(100); return rewardAmount; }
701,423
./full_match/4/0xFf079e56d957284C5F622e9537aD8879236eCa4F/sources/FineCore.sol
set Randomizer/
function setRandom(address rand) external onlyRole(DEFAULT_ADMIN_ROLE) { entropySource = RandomizerInt(rand); }
654,466
//Address: 0x87dde390e9d458dca2692c29facaa33b7636f7fa //Contract name: ERC223Token //Balance: 0 Ether //Verification Date: 2/9/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.19; interface ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract ERC223Token is owned { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); mapping(address => uint) balances; // List of user balances. string _name; string _symbol; uint8 public constant DECIMALS = 6; // 6 decimals is the strongly suggested default, avoid changing it uint256 _totalSupply; address team_addr; uint256 team_keep_amount; uint256 _saledTotal = 0; uint256 _amounToSale = 0; uint _buyPrice = 10; uint256 _totalEther = 0; // Team钱包 300000000 个 address addrTeam = 0xe926f9dbEB503c5b273ba496Af48E8f7d6995C64; // Funder钱包 900000000 个 address addrFounder = 0x6AfD59bAa83d6e0F48cdcb791ABB88d43348c0b7; // Operation钱包 800000000 个 address addrOper = 0x062fCa3A0f33087425837b0f88CfC0d1EE528EFb; // Lynch钱包 400000000 个 address addrLynch = 0x6395075e827D7af7028Dd058C5B432EC624b0c53; // Pool钱包 400000000 个 address addrPool = 0xaA008ba2A493849a2004Ea13E24C8adcBeE63EE6; function ERC223Token( string tokenName, string tokenSymbol ) public { _totalSupply = 4000000000 * 10 ** uint256(DECIMALS); // 实际供应总量 balances[addrTeam] = 300000000 * 10 ** uint256(DECIMALS); balances[addrFounder] = 900000000 * 10 ** uint256(DECIMALS); balances[addrOper] = 800000000 * 10 ** uint256(DECIMALS); balances[addrLynch] = 400000000 * 10 ** uint256(DECIMALS); balances[addrPool] = 400000000 * 10 ** uint256(DECIMALS); _amounToSale = 1200000000 * 10 ** uint256(DECIMALS); _saledTotal = 0; _name = tokenName; // 设置Token名字 _symbol = tokenSymbol; // 设置Token符号 } function name() public constant returns (string) { return _name; } function symbol() public constant returns (string) { return _symbol; } function totalSupply() public constant returns (uint256) { return _totalSupply; } function buyPrice() public constant returns (uint256) { return _buyPrice; } /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint _value, bytes _data) public returns (bool ok) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; require (_to != 0x0); assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } require(balances[msg.sender]>=_value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint _value) public returns(bool ok) { uint codeLength; bytes memory empty; require (_to != 0x0); assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } require(balances[msg.sender]>=_value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } Transfer(msg.sender, _to, _value, empty); return true; } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } function setPrices(uint256 newBuyPrice) onlyOwner public { _buyPrice = newBuyPrice; } function transTo(address _from, address _to, uint256 _amount) onlyOwner public returns(bool ok) { require(balances[_from]>=_amount); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); return true; } /// @notice Buy tokens from contract by sending ether function buyCoin() payable public returns (bool ok) { uint amount = ((msg.value * _buyPrice) * 10 ** uint256(DECIMALS))/1000000000000000000; // calculates the amount require ((_amounToSale - _saledTotal)>=amount); balances[msg.sender] = balances[msg.sender].add(amount); _saledTotal = _saledTotal.add(amount); _totalEther += msg.value; return true; } function dispatchTo(address target, uint256 amount) onlyOwner public returns (bool ok) { require ((_amounToSale - _saledTotal)>=amount); balances[target] = balances[target].add(amount); _saledTotal = _saledTotal.add(amount); return true; } function withdrawTo(address _target, uint256 _value) onlyOwner public returns (bool ok) { require(_totalEther <= _value); _totalEther -= _value; _target.transfer(_value); return true; } function () payable public { } }
Transfer the specified amount of tokens to the specified address. Invokes the `tokenFallback` function if the recipient is a contract. The token transfer fails if the recipient is a contract but does not implement the `tokenFallback` function or the fallback function to receive funds. _to Receiver address. _value Amount of tokens that will be transferred. _data Transaction metadata./ Standard function transfer similar to ERC20 transfer with no _data . Added due to backwards compatibility reasons . Retrieve the size of the code on target address, this needs assembly .
function transfer(address _to, uint _value, bytes _data) public returns (bool ok) { uint codeLength; require (_to != 0x0); assembly { codeLength := extcodesize(_to) } require(balances[msg.sender]>=_value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); return true; }
5,500,297
pragma solidity ^0.4.24; /** * @title It holds the storage variables related to ERC20DividendCheckpoint module */ contract ERC20DividendCheckpointStorage { // Mapping to token address for each dividend mapping (uint256 => address) public dividendTokens; } /** * @title Holds the storage variable for the DividendCheckpoint modules (i.e ERC20, Ether) * @dev abstract contract */ contract DividendCheckpointStorage { // Address to which reclaimed dividends and withholding tax is sent address public wallet; uint256 public EXCLUDED_ADDRESS_LIMIT = 150; bytes32 public constant DISTRIBUTE = "DISTRIBUTE"; bytes32 public constant MANAGE = "MANAGE"; bytes32 public constant CHECKPOINT = "CHECKPOINT"; struct Dividend { uint256 checkpointId; uint256 created; // Time at which the dividend was created uint256 maturity; // Time after which dividend can be claimed - set to 0 to bypass uint256 expiry; // Time until which dividend can be claimed - after this time any remaining amount can be withdrawn by issuer - // set to very high value to bypass uint256 amount; // Dividend amount in WEI uint256 claimedAmount; // Amount of dividend claimed so far uint256 totalSupply; // Total supply at the associated checkpoint (avoids recalculating this) bool reclaimed; // True if expiry has passed and issuer has reclaimed remaining dividend uint256 totalWithheld; uint256 totalWithheldWithdrawn; mapping (address => bool) claimed; // List of addresses which have claimed dividend mapping (address => bool) dividendExcluded; // List of addresses which cannot claim dividends mapping (address => uint256) withheld; // Amount of tax withheld from claim bytes32 name; // Name/title - used for identification } // List of all dividends Dividend[] public dividends; // List of addresses which cannot claim dividends address[] public excluded; // Mapping from address to withholding tax as a percentage * 10**16 mapping (address => uint256) public withholdingTax; } /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function _implementation() internal view returns (address); /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function _fallback() internal { _delegate(_implementation()); } /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function _delegate(address implementation) internal { /*solium-disable-next-line security/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) } } } function () public payable { _fallback(); } } /** * @title OwnedProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedProxy is Proxy { // Owner of the contract address private __owner; // Address of the current implementation address internal __implementation; /** * @dev Event to show ownership has been transferred * @param _previousOwner representing the address of the previous owner * @param _newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address _previousOwner, address _newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier ifOwner() { if (msg.sender == _owner()) { _; } else { _fallback(); } } /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor() public { _setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function _owner() internal view returns (address) { return __owner; } /** * @dev Sets the address of the owner */ function _setOwner(address _newOwner) internal { require(_newOwner != address(0), "Address should not be 0x"); __owner = _newOwner; } /** * @notice Internal function to provide the address of the implementation contract */ function _implementation() internal view returns (address) { return __implementation; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() external ifOwner returns (address) { return _owner(); } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() external ifOwner returns (address) { return _implementation(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferProxyOwnership(address _newOwner) external ifOwner { require(_newOwner != address(0), "Address should not be 0x"); emit ProxyOwnershipTransferred(_owner(), _newOwner); _setOwner(_newOwner); } } /** * @title Utility contract to allow pausing and unpausing of certain functions */ contract Pausable { event Pause(uint256 _timestammp); event Unpause(uint256 _timestamp); bool public paused = false; /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "Contract is paused"); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "Contract is not paused"); _; } /** * @notice Called by the owner to pause, triggers stopped state */ function _pause() internal whenNotPaused { paused = true; /*solium-disable-next-line security/no-block-members*/ emit Pause(now); } /** * @notice Called by the owner to unpause, returns to normal state */ function _unpause() internal whenPaused { paused = false; /*solium-disable-next-line security/no-block-members*/ emit Unpause(now); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool); function increaseApproval(address _spender, uint _addedValue) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Storage for Module contract * @notice Contract is abstract */ contract ModuleStorage { /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public { securityToken = _securityToken; factory = msg.sender; polyToken = IERC20(_polyAddress); } address public factory; address public securityToken; bytes32 public constant FEE_ADMIN = "FEE_ADMIN"; IERC20 public polyToken; } /** * @title Transfer Manager module for core transfer validation functionality */ contract ERC20DividendCheckpointProxy is ERC20DividendCheckpointStorage, DividendCheckpointStorage, ModuleStorage, Pausable, OwnedProxy { /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken * @param _implementation representing the address of the new implementation to be set */ constructor (address _securityToken, address _polyAddress, address _implementation) public ModuleStorage(_securityToken, _polyAddress) { require( _implementation != address(0), "Implementation address should not be 0x" ); __implementation = _implementation; } } /** * @title Utility contract for reusable code */ library Util { /** * @notice Changes a string to upper case * @param _base String to change */ function upper(string _base) internal pure returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { bytes1 b1 = _baseBytes[i]; if (b1 >= 0x61 && b1 <= 0x7A) { b1 = bytes1(uint8(b1)-32); } _baseBytes[i] = b1; } return string(_baseBytes); } /** * @notice Changes the string into bytes32 * @param _source String that need to convert into bytes32 */ /// Notice - Maximum Length for _source will be 32 chars otherwise returned bytes32 value will have lossy value. function stringToBytes32(string memory _source) internal pure returns (bytes32) { return bytesToBytes32(bytes(_source), 0); } /** * @notice Changes bytes into bytes32 * @param _b Bytes that need to convert into bytes32 * @param _offset Offset from which to begin conversion */ /// Notice - Maximum length for _source will be 32 chars otherwise returned bytes32 value will have lossy value. function bytesToBytes32(bytes _b, uint _offset) internal pure returns (bytes32) { bytes32 result; for (uint i = 0; i < _b.length; i++) { result |= bytes32(_b[_offset + i] & 0xFF) >> (i * 8); } return result; } /** * @notice Changes the bytes32 into string * @param _source that need to convert into string */ function bytes32ToString(bytes32 _source) internal pure returns (string result) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(_source) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } /** * @notice Gets function signature from _data * @param _data Passed data * @return bytes4 sig */ function getSig(bytes _data) internal pure returns (bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint i = 0; i < len; i++) { sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i)))); } } } interface IBoot { /** * @notice This function returns the signature of configure function * @return bytes4 Configure function signature */ function getInitFunction() external pure returns(bytes4); } /** * @title Interface that every module factory contract should implement */ interface IModuleFactory { event ChangeFactorySetupFee(uint256 _oldSetupCost, uint256 _newSetupCost, address _moduleFactory); event ChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory); event ChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory); event GenerateModuleFromFactory( address _module, bytes32 indexed _moduleName, address indexed _moduleFactory, address _creator, uint256 _setupCost, uint256 _timestamp ); event ChangeSTVersionBound(string _boundType, uint8 _major, uint8 _minor, uint8 _patch); //Should create an instance of the Module, or throw function deploy(bytes _data) external returns(address); /** * @notice Type of the Module factory */ function getTypes() external view returns(uint8[]); /** * @notice Get the name of the Module */ function getName() external view returns(bytes32); /** * @notice Returns the instructions associated with the module */ function getInstructions() external view returns (string); /** * @notice Get the tags related to the module factory */ function getTags() external view returns (bytes32[]); /** * @notice Used to change the setup fee * @param _newSetupCost New setup fee */ function changeFactorySetupFee(uint256 _newSetupCost) external; /** * @notice Used to change the usage fee * @param _newUsageCost New usage fee */ function changeFactoryUsageFee(uint256 _newUsageCost) external; /** * @notice Used to change the subscription fee * @param _newSubscriptionCost New subscription fee */ function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) external; /** * @notice Function use to change the lower and upper bound of the compatible version st * @param _boundType Type of bound * @param _newVersion New version array */ function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external; /** * @notice Get the setup cost of the module */ function getSetupCost() external view returns (uint256); /** * @notice Used to get the lower bound * @return Lower bound */ function getLowerSTVersionBounds() external view returns(uint8[]); /** * @notice Used to get the upper bound * @return Upper bound */ function getUpperSTVersionBounds() external view returns(uint8[]); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ 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; } } /** * @title Helper library use to compare or validate the semantic versions */ library VersionUtils { /** * @notice This function is used to validate the version submitted * @param _current Array holds the present version of ST * @param _new Array holds the latest version of the ST * @return bool */ function isValidVersion(uint8[] _current, uint8[] _new) internal pure returns(bool) { bool[] memory _temp = new bool[](_current.length); uint8 counter = 0; for (uint8 i = 0; i < _current.length; i++) { if (_current[i] < _new[i]) _temp[i] = true; else _temp[i] = false; } for (i = 0; i < _current.length; i++) { if (i == 0) { if (_current[i] <= _new[i]) if(_temp[0]) { counter = counter + 3; break; } else counter++; else return false; } else { if (_temp[i-1]) counter++; else if (_current[i] <= _new[i]) counter++; else return false; } } if (counter == _current.length) return true; } /** * @notice Used to compare the lower bound with the latest version * @param _version1 Array holds the lower bound of the version * @param _version2 Array holds the latest version of the ST * @return bool */ function compareLowerBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) { require(_version1.length == _version2.length, "Input length mismatch"); uint counter = 0; for (uint8 j = 0; j < _version1.length; j++) { if (_version1[j] == 0) counter ++; } if (counter != _version1.length) { counter = 0; for (uint8 i = 0; i < _version1.length; i++) { if (_version2[i] > _version1[i]) return true; else if (_version2[i] < _version1[i]) return false; else counter++; } if (counter == _version1.length - 1) return true; else return false; } else return true; } /** * @notice Used to compare the upper bound with the latest version * @param _version1 Array holds the upper bound of the version * @param _version2 Array holds the latest version of the ST * @return bool */ function compareUpperBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) { require(_version1.length == _version2.length, "Input length mismatch"); uint counter = 0; for (uint8 j = 0; j < _version1.length; j++) { if (_version1[j] == 0) counter ++; } if (counter != _version1.length) { counter = 0; for (uint8 i = 0; i < _version1.length; i++) { if (_version1[i] > _version2[i]) return true; else if (_version1[i] < _version2[i]) return false; else counter++; } if (counter == _version1.length - 1) return true; else return false; } else return true; } /** * @notice Used to pack the uint8[] array data into uint24 value * @param _major Major version * @param _minor Minor version * @param _patch Patch version */ function pack(uint8 _major, uint8 _minor, uint8 _patch) internal pure returns(uint24) { return (uint24(_major) << 16) | (uint24(_minor) << 8) | uint24(_patch); } /** * @notice Used to convert packed data into uint8 array * @param _packedVersion Packed data */ function unpack(uint24 _packedVersion) internal pure returns (uint8[]) { uint8[] memory _unpackVersion = new uint8[](3); _unpackVersion[0] = uint8(_packedVersion >> 16); _unpackVersion[1] = uint8(_packedVersion >> 8); _unpackVersion[2] = uint8(_packedVersion); return _unpackVersion; } } /** * @title Interface that any module factory contract should implement * @notice Contract is abstract */ contract ModuleFactory is IModuleFactory, Ownable { IERC20 public polyToken; uint256 public usageCost; uint256 public monthlySubscriptionCost; uint256 public setupCost; string public description; string public version; bytes32 public name; string public title; // @notice Allow only two variables to be stored // 1. lowerBound // 2. upperBound // @dev (0.0.0 will act as the wildcard) // @dev uint24 consists packed value of uint8 _major, uint8 _minor, uint8 _patch mapping(string => uint24) compatibleSTVersionRange; /** * @notice Constructor * @param _polyAddress Address of the polytoken */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public { polyToken = IERC20(_polyAddress); setupCost = _setupCost; usageCost = _usageCost; monthlySubscriptionCost = _subscriptionCost; } /** * @notice Used to change the fee of the setup cost * @param _newSetupCost new setup cost */ function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner { emit ChangeFactorySetupFee(setupCost, _newSetupCost, address(this)); setupCost = _newSetupCost; } /** * @notice Used to change the fee of the usage cost * @param _newUsageCost new usage cost */ function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner { emit ChangeFactoryUsageFee(usageCost, _newUsageCost, address(this)); usageCost = _newUsageCost; } /** * @notice Used to change the fee of the subscription cost * @param _newSubscriptionCost new subscription cost */ function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner { emit ChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this)); monthlySubscriptionCost = _newSubscriptionCost; } /** * @notice Updates the title of the ModuleFactory * @param _newTitle New Title that will replace the old one. */ function changeTitle(string _newTitle) public onlyOwner { require(bytes(_newTitle).length > 0, "Invalid title"); title = _newTitle; } /** * @notice Updates the description of the ModuleFactory * @param _newDesc New description that will replace the old one. */ function changeDescription(string _newDesc) public onlyOwner { require(bytes(_newDesc).length > 0, "Invalid description"); description = _newDesc; } /** * @notice Updates the name of the ModuleFactory * @param _newName New name that will replace the old one. */ function changeName(bytes32 _newName) public onlyOwner { require(_newName != bytes32(0),"Invalid name"); name = _newName; } /** * @notice Updates the version of the ModuleFactory * @param _newVersion New name that will replace the old one. */ function changeVersion(string _newVersion) public onlyOwner { require(bytes(_newVersion).length > 0, "Invalid version"); version = _newVersion; } /** * @notice Function use to change the lower and upper bound of the compatible version st * @param _boundType Type of bound * @param _newVersion new version array */ function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external onlyOwner { require( keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) || keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("upperBound")), "Must be a valid bound type" ); require(_newVersion.length == 3); if (compatibleSTVersionRange[_boundType] != uint24(0)) { uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]); require(VersionUtils.isValidVersion(_currentVersion, _newVersion), "Failed because of in-valid version"); } compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]); emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]); } /** * @notice Used to get the lower bound * @return lower bound */ function getLowerSTVersionBounds() external view returns(uint8[]) { return VersionUtils.unpack(compatibleSTVersionRange["lowerBound"]); } /** * @notice Used to get the upper bound * @return upper bound */ function getUpperSTVersionBounds() external view returns(uint8[]) { return VersionUtils.unpack(compatibleSTVersionRange["upperBound"]); } /** * @notice Get the setup cost of the module */ function getSetupCost() external view returns (uint256) { return setupCost; } /** * @notice Get the name of the Module */ function getName() public view returns(bytes32) { return name; } } /** * @title Factory for deploying ERC20DividendCheckpoint module */ contract ERC20DividendCheckpointFactory is ModuleFactory { address public logicContract; /** * @notice Constructor * @param _polyAddress Address of the polytoken * @param _setupCost Setup cost of the module * @param _usageCost Usage cost of the module * @param _subscriptionCost Subscription cost of the module * @param _logicContract Contract address that contains the logic related to `description` */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost, address _logicContract) public ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) { require(_logicContract != address(0), "Invalid logic contract"); version = "2.1.1"; name = "ERC20DividendCheckpoint"; title = "ERC20 Dividend Checkpoint"; description = "Create ERC20 dividends for token holders at a specific checkpoint"; compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); logicContract = _logicContract; } /** * @notice Used to launch the Module with the help of factory * @return Address Contract address of the Module */ function deploy(bytes _data) external returns(address) { if (setupCost > 0) require(polyToken.transferFrom(msg.sender, owner, setupCost), "insufficent allowance"); address erc20DividendCheckpoint = new ERC20DividendCheckpointProxy(msg.sender, address(polyToken), logicContract); //Checks that _data is valid (not calling anything it shouldn't) require(Util.getSig(_data) == IBoot(erc20DividendCheckpoint).getInitFunction(), "Invalid data"); /*solium-disable-next-line security/no-low-level-calls*/ require(erc20DividendCheckpoint.call(_data), "Unsuccessfull call"); /*solium-disable-next-line security/no-block-members*/ emit GenerateModuleFromFactory(erc20DividendCheckpoint, getName(), address(this), msg.sender, setupCost, now); return erc20DividendCheckpoint; } /** * @notice Type of the Module factory */ function getTypes() external view returns(uint8[]) { uint8[] memory res = new uint8[](1); res[0] = 4; return res; } /** * @notice Returns the instructions associated with the module */ function getInstructions() external view returns(string) { return "Create ERC20 dividend to be paid out to token holders based on their balances at dividend creation time"; } /** * @notice Get the tags related to the module factory */ function getTags() external view returns(bytes32[]) { bytes32[] memory availableTags = new bytes32[](3); availableTags[0] = "ERC20"; availableTags[1] = "Dividend"; availableTags[2] = "Checkpoint"; return availableTags; } }
Changes the string into bytes32 _source String that need to convert into bytes32/ Notice - Maximum Length for _source will be 32 chars otherwise returned bytes32 value will have lossy value.
function stringToBytes32(string memory _source) internal pure returns (bytes32) { return bytesToBytes32(bytes(_source), 0); }
926,209
./partial_match/1/0x9C3AFDDEa87a726891A44C037242393D524CAcFE/sources/contracts/PancakeV3Factory.sol
@inheritdoc IPancakeV3Factory tick spacing is capped at 16384 to prevent the situation where tickSpacing is so large that TickBitmapnextInitializedTickWithinOneWord overflows int24 container from a valid tick 16384 ticks represents a >5x price change with ticks of 1 bips
function enableFeeAmount(uint24 fee, int24 tickSpacing) public override onlyOwner { require(fee < 1000000); require(tickSpacing > 0 && tickSpacing < 16384); require(feeAmountTickSpacing[fee] == 0); feeAmountTickSpacing[fee] = tickSpacing; emit FeeAmountEnabled(fee, tickSpacing); emit FeeAmountExtraInfoUpdated(fee, false, true); }
2,749,026
./full_match/4/0x1Ca18a09c59ee102070399D37bc3aEa54Fa102Cc/sources/browser/myERC20.sol
Reclaim all ERC20Basic compatible tokens token ERC20B The address of the token contract/
function reclaimToken(ERC20 token) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(owner, balance); }
12,432,399
pragma solidity >=0.4.0 <0.6.0; pragma experimental ABIEncoderV2; import "remix_tests.sol"; // this import is automatically injected by Remix. import "./AccessRightManager.sol"; // file name has to end with '_test.sol' contract test_1 { AccessRightsManagement arm; function beforeAll() public { // here should instantiate tested contract arm = new AccessRightsManagement(); bool result = arm.welcome("bla"); Assert.equal(result, false, "user bla should not be recognised"); result = arm.welcome("test"); Assert.equal(result, true, "user test should be recognised"); bool newresult = arm.proceedWelcome("bla","Please let me in"); Assert.equal(newresult, true, "user should be able to requesst accoutn generation"); result = arm.proceedWelcome("bla","Please let me in bro"); Assert.equal(result, false, "user should not be able to requesst accoutn generation again"); /** string memory message = arm.getCreationRequest("test"); Assert.equal(true, (bytes(message).length > 0), "user message should be there"); int8[4] memory a; a[2] = 2; Assert.equal(true, arm.getQueue().length == 1, "Queue should have 1 element now"); arm.handleCreationRequest("test",true,0x65787465726e616c000000000000000000000000000000000000000000000000,"deliverer",a,[false,false,false,false,false]); Assert.equal(true, arm.getUser("bla").hasAccessRight[2] == 2, "user should have assigned access right"); Assert.equal(true, arm.getQueue().length == 0,"Queue should be empty now"); */ } function check1() public { // arm = new AccessRightsManagement(); // bool result = arm.proceedWelcome("bla","Please let me in bro"); //Assert.equal(result, false, "user should not be able to requesst accoutn generation again"); string memory message = arm.getCreationRequest("test"); Assert.equal(true, (bytes(message).length > 0), "user message should be there"); int8[4] memory a; a[2] = 2; Assert.equal(true, arm.getQueue().length == 1, "Queue should have 1 element now"); arm.handleCreationRequest("test",true,0x65787465726e616c000000000000000000000000000000000000000000000000,"deliverer",a,[false,false,false,false,false]); // Assert.equal(true, arm.getUser("bla").hasAccessRight[2] == 2, "user should have assigned access right"); //Assert.equal(true, arm.getQueue().length == 0,"Queue should be empty now"); int8 newright = arm.newAccessRight("bla",1); Assert.equal(true, newright == 0,"access right before should be 0"); arm.newAccessRight("bla",1); // bool allowed = arm.handleRequest("test",0,1,true); // Assert.equal(true, allowed,"access right should be granted"); } } /** function check2() public view returns (bool) { // use the return value (true or false) to test the contract return true; } } /** contract test_2 { function beforeAll() public { // here should instantiate tested contract Assert.equal(uint(4), uint(3), "error in before all function"); } function check1() public { // use 'Assert' to test the contract Assert.equal(uint(2), uint(1), "error message"); Assert.equal(uint(2), uint(2), "error message"); } function check2() public view returns (bool) { // use the return value (true or false) to test the contract return true; } } */
arm = new AccessRightsManagement(); bool result = arm.proceedWelcome("bla","Please let me in bro");Assert.equal(result, false, "user should not be able to requesst accoutn generation again"); Assert.equal(true, arm.getUser("bla").hasAccessRight[2] == 2, "user should have assigned access right");Assert.equal(true, arm.getQueue().length == 0,"Queue should be empty now"); bool allowed = arm.handleRequest("test",0,1,true); Assert.equal(true, allowed,"access right should be granted");
function check1() public { string memory message = arm.getCreationRequest("test"); Assert.equal(true, (bytes(message).length > 0), "user message should be there"); int8[4] memory a; a[2] = 2; Assert.equal(true, arm.getQueue().length == 1, "Queue should have 1 element now"); arm.handleCreationRequest("test",true,0x65787465726e616c000000000000000000000000000000000000000000000000,"deliverer",a,[false,false,false,false,false]); int8 newright = arm.newAccessRight("bla",1); Assert.equal(true, newright == 0,"access right before should be 0"); arm.newAccessRight("bla",1); }
12,994,123
./partial_match/3/0x76cbFEFe70214372e43643052c32d0ca9e428CFB/sources/cmtFoundingToken.sol
usdt to governancetoken to spenderuint share = _amount.div(2);transferFrom(governance, msg.sender, share);
function swapUSDT(uint _amount) public { require(isOpenSwap == 1, "!isOpenSwap"); require(_amount >=min_unit, "!min _amount "); uint maxShares = balanceOfGOV(); require(_amount <=maxShares, "!max _amount "); token.safeApprove(msg.sender, _amount); token.safeTransferFrom(msg.sender, governance, _amount); }
5,208,364
pragma solidity ^0.4.24; contract F4Devents { event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount, uint256 potAmount ); event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract Fomo4D is F4Devents { using SafeMath for *; using NameFilter for string; using F4DKeysCalcLong for uint256; address private owner_; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xeEd618C15d12C635C3C319aEe7BDED2E2879AEa0); string constant public name = "Fomo4D"; string constant public symbol = "F4D"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be uint256 public rID_; // round id number / total rounds that have happened mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F4Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F4Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) mapping (uint256 => F4Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id mapping (uint256 => F4Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F4Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team constructor() public { owner_ = msg.sender; // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls fees_[0] = F4Ddatasets.TeamFee(24); fees_[1] = F4Ddatasets.TeamFee(38); fees_[2] = F4Ddatasets.TeamFee(50); fees_[3] = F4Ddatasets.TeamFee(42); potSplit_[0] = F4Ddatasets.PotSplit(12); potSplit_[1] = F4Ddatasets.PotSplit(19); potSplit_[2] = F4Ddatasets.PotSplit(26); potSplit_[3] = F4Ddatasets.PotSplit(30); } //modifier /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //public functions /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F4Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F4Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F4Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F4Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F4Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F4Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //view /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( 0, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3] //12 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //core logic /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F4Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F4Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F4Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F4Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F4Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _affID, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( ( ( (round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys) ) / (1000000000000000000) ).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F4Ddatasets.EventReturns memory _eventData_) private returns (F4Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F4Ddatasets.EventReturns memory _eventData_) private returns (F4Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F4Ddatasets.EventReturns memory _eventData_) private returns (F4Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _own = (_pot.mul(14) / 100); owner_.transfer(_own); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_own)).sub(_gen)); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, F4Ddatasets.EventReturns memory _eventData_) private returns(F4Ddatasets.EventReturns) { // pay 14% out to owner rewards uint256 _own = _eth.mul(14) / 100; owner_.transfer(_own); return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F4Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, uint256 _keys, F4Ddatasets.EventReturns memory _eventData_) private returns(F4Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // distribute share to affiliate 10% uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F4Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _gen = _gen.add(_aff); _aff = 0; } // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub((_eth.mul(14)) / 100); // calculate pot uint256 _pot = _eth.sub(_gen).sub(_aff); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) { _gen = _gen.sub(_dust); _pot = _pot.add(_dust); } // add eth to pot round_[_rID].pot = _pot.add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F4Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F4Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount ); } /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == owner_, "only team just can activate" ); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } //structs library F4Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round } } library F4DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return( keys((_curEth).add(_newEth)) .sub( keys(_curEth) ) ); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { // (sqrt(_eth * 10^18 * 312500000 * 10 ^ 18 + 5624988281256103515625000000000000000000000000 * 10 ^ 18) - 74999921875000 * 10 ^ 18) / 156250000 return ( ( ( ( ( (_eth).mul(1000000000000000000) ).mul(312500000000000000000000000) ).add(5624988281256103515625000000000000000000000000000000000000000000) ).sqrt() ).sub(74999921875000000000000000000000) ) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
calculates unmasked earnings (just calculates, does not update mask) return earnings in wei format/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( ( ( (round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys) ) / (1000000000000000000) ).sub(plyrRnds_[_pID][_rIDlast].mask) ); }
10,117,711
/* Implements EIP918 draft token standard: https://github.com/0xbitcoin/ERC541-Spec/blob/master/contracts/EIP541.sol .*/ pragma solidity ^0.4.18; import "./EIP20Interface.sol"; import "./AbstractERC918.sol"; import "./SafeMath.sol"; import "./ExtendedMath.sol"; import "./Owned.sol"; /** * _0xBitcoinBase Implementation used for creating ERC918, ERC20 mineable tokens using the same difficulty * adjustment, reward and hashing features of 0xBitcoin * * This complex contract implements a minimal set of behaviors (hash, reward, epoch, and difficulty adjustment) * and state required to build a Proof of Work driven mineable token. Refactoring of 0xBitcoin base code to be * used for implementing 0xbitcoin based mineable tokens * * https://github.com/ethereum/EIPs/pull/918 * https://github.com/0xbitcoin/0xbitcoin-token/blob/master/contracts/_0xBitcoinToken.sol */ contract _0xBitcoinBase is AbstractERC918, EIP20Interface { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint256 public totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount;//number of 'blocks' mined uint public baseMiningReward; uint public blocksPerReadjustment; uint public _MINIMUM_TARGET = 2**16; uint public _MAXIMUM_TARGET = 2**234; uint public rewardEra; uint public maxSupplyForEra; uint public MAX_REWARD_ERA = 39; uint public MINING_RATE_FACTOR = 60; //mint the token 60 times less often than ether //difficulty adjustment parameters- be careful modifying these uint public MAX_ADJUSTMENT_PERCENT = 100; uint public TARGET_DIVISOR = 2000; uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2); mapping(bytes32 => bytes32) solutionForChallenge; mapping(address => mapping(address => uint)) allowed; // balances of mapping(address => uint) balances; /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function _0xBitcoinBase( string tokenSymbol, string tokenName, uint256 tokenSupply, uint8 tokenDecimals, uint initialReward, uint blocksPerDifficultyAdjustment ) public { symbol = tokenSymbol; name = tokenName; decimals = tokenDecimals; totalSupply = tokenSupply * 10**uint(decimals); baseMiningReward = initialReward; blocksPerReadjustment = blocksPerDifficultyAdjustment; // -- do not change lines below -- tokensMinted = 0; rewardEra = 0; maxSupplyForEra = totalSupply.div(2); difficulty = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; _newEpoch(0); } function _hash(uint256 nonce, bytes32 challenge_digest) internal returns (bytes32 digest) { digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > difficulty) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice } //21m coins total //reward begins at 50 and is cut in half every reward era (as tokens are mined) function _reward() internal returns (uint) { //once we get half way thru the coins, only get 25 per block //every reward era, the reward amount halves. uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); return reward_amount; } function _newEpoch(uint256 nonce) internal returns (uint) { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //40 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA) { rewardEra = rewardEra + 1; } //set the next minted supply at which the era will change // total supply is 2100000000000000 because of 8 decimal places maxSupplyForEra = totalSupply - totalSupply.div( 2**(rewardEra + 1)); epochCount = epochCount.add(1); //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } //DO NOT manually edit this method unless you know EXACTLY what you are doing function _adjustDifficulty() internal returns (uint) { //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % blocksPerReadjustment != 0){ return difficulty; } uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 360 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 60 ethereum blocks = one 0xbitcoin epoch uint epochsMined = blocksPerReadjustment; uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR; //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra)); //by up to 50 % }else{ uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); //always between 0 and 1000 //make it easier difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(difficulty < _MINIMUM_TARGET) //very difficult { difficulty = _MINIMUM_TARGET; } if(difficulty > _MAXIMUM_TARGET) //very easy { difficulty = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(difficulty); } function getMiningTarget() public constant returns (uint) { return difficulty; } //21m coins total //reward begins at 50 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 25 per block //every reward era, the reward amount halves. return (baseMiningReward * 10**uint(decimals) ).div( 2**rewardEra ) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; }
this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; }
951,764
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "./erc677/IERC677Receiver.sol"; import "./access/HasCrunchParent.sol"; import "./CrunchToken.sol"; /** * DataCrunch Staking contract for the CRUNCH token. * * To start staking, use the {CrunchStaking-deposit(address)} method, but this require an allowance from your account. * Another method is to do a {CrunchToken-transferAndCall(address, uint256, bytes)} to avoid doing 2 transactions. (as per ERC-677 standart) * * Withdrawing will withdraw everything. There is currently no method to only withdraw a specific amount. * * @author Enzo CACERES * @author Arnaud CASTILLO */ contract CrunchStaking is HasCrunchParent, IERC677Receiver { event Withdrawed( address indexed to, uint256 reward, uint256 staked, uint256 totalAmount ); event EmergencyWithdrawed(address indexed to, uint256 staked); event Deposited(address indexed sender, uint256 amount); event RewardPerDayUpdated(uint256 rewardPerDay, uint256 totalDebt); struct Holder { /** Index in `addresses`, used for faster lookup in case of a remove. */ uint256 index; /** When does an holder stake for the first time (set to `block.timestamp`). */ uint256 start; /** Total amount staked by the holder. */ uint256 totalStaked; /** When the reward per day is updated, the reward debt is updated to ensure that the previous reward they could have got isn't lost. */ uint256 rewardDebt; /** Individual stakes. */ Stake[] stakes; } struct Stake { /** How much the stake is. */ uint256 amount; /** When does the stakes 'start' is. When created it is `block.timestamp`, and is updated when the `reward per day` is updated. */ uint256 start; } /** The `reward per day` is the amount of tokens rewarded for 1 million CRUNCHs staked over a 1 day period. */ uint256 public rewardPerDay; /** List of all currently staking addresses. Used for looping. */ address[] public addresses; /** address to Holder mapping. */ mapping(address => Holder) public holders; /** Currently total staked amount by everyone. It is incremented when someone deposit token, and decremented when someone withdraw. This value does not include the rewards. */ uint256 public totalStaked; /** @dev Initializes the contract by specifying the parent `crunch` and the initial `rewardPerDay`. */ constructor(CrunchToken crunch, uint256 _rewardPerDay) HasCrunchParent(crunch) { rewardPerDay = _rewardPerDay; } /** * @dev Deposit an `amount` of tokens from your account to this contract. * * This will start the staking with the provided amount. * The implementation call {IERC20-transferFrom}, so the caller must have previously {IERC20-approve} the `amount`. * * Emits a {Deposited} event. * * Requirements: * - `amount` cannot be the zero address. * - `caller` must have a balance of at least `amount`. * * @param amount amount to reposit. */ function deposit(uint256 amount) external { crunch.transferFrom(_msgSender(), address(this), amount); _deposit(_msgSender(), amount); } /** * Withdraw the staked tokens with the reward. * * Emits a {Withdrawed} event. * * Requirements: * - `caller` to be staking. */ function withdraw() external { _withdraw(_msgSender()); } /** * Returns the current reserve for rewards. * * @return the contract balance - the total staked. */ function reserve() public view returns (uint256) { uint256 balance = contractBalance(); if (totalStaked > balance) { revert( "Staking: the balance has less CRUNCH than the total staked" ); } return balance - totalStaked; } /** * Test if the caller is currently staking. * * @return `true` if the caller is staking, else if not. */ function isCallerStaking() external view returns (bool) { return isStaking(_msgSender()); } /** * Test if an address is currently staking. * * @param `addr` address to test. * @return `true` if the address is staking, else if not. */ function isStaking(address addr) public view returns (bool) { return _isStaking(holders[addr]); } /** * Get the current balance in CRUNCH of this smart contract. * * @return The current staking contract's balance in CRUNCH. */ function contractBalance() public view returns (uint256) { return crunch.balanceOf(address(this)); } /** * Returns the sum of the specified `addr` staked amount. * * @param addr address to check. * @return the total staked of the holder. */ function totalStakedOf(address addr) external view returns (uint256) { return holders[addr].totalStaked; } /** * Returns the computed reward of everyone. * * @return total the computed total reward of everyone. */ function totalReward() public view returns (uint256 total) { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; total += totalRewardOf(addr); } } /** * Compute the reward of the specified `addr`. * * @param addr address to test. * @return the reward the address would get. */ function totalRewardOf(address addr) public view returns (uint256) { Holder storage holder = holders[addr]; return _computeRewardOf(holder); } /** * Sum the reward debt of everyone. * * @return total the sum of all `Holder.rewardDebt`. */ function totalRewardDebt() external view returns (uint256 total) { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; total += rewardDebtOf(addr); } } /** * Get the reward debt of an holder. * * @param addr holder's address. * @return the reward debt of the holder. */ function rewardDebtOf(address addr) public view returns (uint256) { return holders[addr].rewardDebt; } /** * Test if the reserve is sufficient to cover the `{totalReward()}`. * * @return whether the reserve has enough CRUNCH to give to everyone. */ function isReserveSufficient() external view returns (bool) { return _isReserveSufficient(totalReward()); } /** * Test if the reserve is sufficient to cover the `{totalRewardOf(address)}` of the specified address. * * @param addr address to test. * @return whether the reserve has enough CRUNCH to give to this address. */ function isReserveSufficientFor(address addr) external view returns (bool) { return _isReserveSufficient(totalRewardOf(addr)); } /** * Get the number of address current staking. * * @return the length of the `addresses` array. */ function stakerCount() external view returns (uint256) { return addresses.length; } /** * Get the stakes array of an holder. * * @param addr address to get the stakes array. * @return the holder's stakes array. */ function stakesOf(address addr) external view returns (Stake[] memory) { return holders[addr].stakes; } /** * Get the stakes array length of an holder. * * @param addr address to get the stakes array length. * @return the length of the `stakes` array. */ function stakesCountOf(address addr) external view returns (uint256) { return holders[addr].stakes.length; } /** * @dev ONLY FOR EMERGENCY!! * * Force an address to withdraw. * * @dev Should only be called if a {CrunchStaking-destroy()} would cost too much gas to be executed. * * @param addr address to withdraw. */ function forceWithdraw(address addr) external onlyOwner { _withdraw(addr); } /** * @dev ONLY FOR EMERGENCY!! * * Emergency withdraw. * * All rewards are discarded. Only initial staked amount will be transfered back! * * Emits a {EmergencyWithdrawed} event. * * Requirements: * - `caller` to be staking. */ function emergencyWithdraw() external { _emergencyWithdraw(_msgSender()); } /** * @dev ONLY FOR EMERGENCY!! * * Force an address to emergency withdraw. * * @dev Should only be called if a {CrunchStaking-emergencyDestroy()} would cost too much gas to be executed. * * @param addr address to emergency withdraw. */ function forceEmergencyWithdraw(address addr) external onlyOwner { _emergencyWithdraw(addr); } /** * Update the reward per day. * * This will recompute a reward debt with the previous reward per day value. * The debt is used to make sure that everyone will keep their rewarded tokens using the previous reward per day value for the calculation. * * Emits a {RewardPerDayUpdated} event. * * Requirements: * - `to` must not be the same as the reward per day. * - `to` must be below or equal to 15000. * * @param to new reward per day value. */ function setRewardPerDay(uint256 to) external onlyOwner { require( rewardPerDay != to, "Staking: reward per day value must be different" ); require( to <= 15000, "Staking: reward per day must be below 15000/1M token/day" ); uint256 debt = _updateDebts(); rewardPerDay = to; emit RewardPerDayUpdated(rewardPerDay, debt); } /** * @dev ONLY FOR EMERGENCY!! * * Empty the reserve if there is a problem. */ function emptyReserve() external onlyOwner { uint256 amount = reserve(); require(amount != 0, "Staking: reserve is empty"); crunch.transfer(owner(), amount); } /** * Destroy the contact after withdrawing everyone. * * @dev If the reserve is not zero after the withdraw, the remaining will be sent back to the contract's owner. */ function destroy() external onlyOwner { uint256 usable = reserve(); uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; Holder storage holder = holders[addr]; uint256 reward = _computeRewardOf(holder); require(usable >= reward, "Staking: reserve does not have enough"); uint256 total = holder.totalStaked + reward; crunch.transfer(addr, total); } _transferRemainingAndSelfDestruct(); } /** * @dev ONLY FOR EMERGENCY!! * * Destroy the contact after emergency withdrawing everyone, avoiding the reward computation to save gas. * * If the reserve is not zero after the withdraw, the remaining will be sent back to the contract's owner. */ function emergencyDestroy() external onlyOwner { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; Holder storage holder = holders[addr]; crunch.transfer(addr, holder.totalStaked); } _transferRemainingAndSelfDestruct(); } /** * @dev ONLY FOR CRITICAL EMERGENCY!! * * Destroy the contact without withdrawing anyone. * Only use this function if the code has a fatal bug and its not possible to do otherwise. */ function criticalDestroy() external onlyOwner { _transferRemainingAndSelfDestruct(); } /** @dev Internal function called when the {IERC677-transferAndCall} is used. */ function onTokenTransfer( address sender, uint256 value, bytes memory data ) external override onlyCrunchParent { data; /* silence unused */ _deposit(sender, value); } /** * Deposit. * * @dev If the depositor is not currently holding, the `Holder.start` is set and his address is added to the addresses list. * * @param from depositor address. * @param amount amount to deposit. */ function _deposit(address from, uint256 amount) internal { require(amount != 0, "cannot deposit zero"); Holder storage holder = holders[from]; if (!_isStaking(holder)) { holder.start = block.timestamp; holder.index = addresses.length; addresses.push(from); } holder.totalStaked += amount; holder.stakes.push(Stake({amount: amount, start: block.timestamp})); totalStaked += amount; emit Deposited(from, amount); } /** * Withdraw. * * @dev This will remove the `Holder` from the `holders` mapping and the address from the `addresses` array. * * Requirements: * - `addr` must be staking. * - the reserve must have enough token. * * @param addr address to withdraw. */ function _withdraw(address addr) internal { Holder storage holder = holders[addr]; require(_isStaking(holder), "Staking: no stakes"); uint256 reward = _computeRewardOf(holder); require( _isReserveSufficient(reward), "Staking: the reserve does not have enough token" ); uint256 staked = holder.totalStaked; uint256 total = staked + reward; crunch.transfer(addr, total); totalStaked -= staked; _deleteAddress(holder.index); delete holders[addr]; emit Withdrawed(addr, reward, staked, total); } /** * Emergency withdraw. * * This is basically the same as {CrunchStaking-_withdraw(address)}, but without the reward. * This function must only be used for emergencies as it consume less gas and does not have the check for the reserve. * * @dev This will remove the `Holder` from the `holders` mapping and the address from the `addresses` array. * * Requirements: * - `addr` must be staking. * * @param addr address to withdraw. */ function _emergencyWithdraw(address addr) internal { Holder storage holder = holders[addr]; require(_isStaking(holder), "Staking: no stakes"); uint256 staked = holder.totalStaked; crunch.transfer(addr, staked); totalStaked -= staked; _deleteAddress(holder.index); delete holders[addr]; emit EmergencyWithdrawed(addr, staked); } /** * Test if the `reserve` is sufficiant for a specified reward. * * @param reward value to test. * @return if the reserve is bigger or equal to the `reward` parameter. */ function _isReserveSufficient(uint256 reward) private view returns (bool) { return reserve() >= reward; } /** * Test if an holder struct is currently staking. * * @dev Its done by testing if the stake array length is equal to zero. Since its not possible, it mean that the holder is not currently staking and the struct is only zero. * * @param holder holder struct. * @return `true` if the holder is staking, `false` otherwise. */ function _isStaking(Holder storage holder) internal view returns (bool) { return holder.stakes.length != 0; } /** * Update the reward debt of all holders. * * @dev Usually called before a `reward per day` update. * * @return total total debt updated. */ function _updateDebts() internal returns (uint256 total) { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; Holder storage holder = holders[addr]; uint256 debt = _updateDebtsOf(holder); holder.rewardDebt += debt; total += debt; } } /** * Update the reward debt of a specified `holder`. * * @param holder holder struct to update. * @return total sum of debt added. */ function _updateDebtsOf(Holder storage holder) internal returns (uint256 total) { uint256 length = holder.stakes.length; for (uint256 index = 0; index < length; index++) { Stake storage stake = holder.stakes[index]; total += _computeStakeReward(stake); stake.start = block.timestamp; } } /** * Compute the reward for every holder. * * @return total the total of all of the reward for all of the holders. */ function _computeTotalReward() internal view returns (uint256 total) { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; Holder storage holder = holders[addr]; total += _computeRewardOf(holder); } } /** * Compute all stakes reward for an holder. * * @param holder the holder struct. * @return total total reward for the holder (including the debt). */ function _computeRewardOf(Holder storage holder) internal view returns (uint256 total) { uint256 length = holder.stakes.length; for (uint256 index = 0; index < length; index++) { Stake storage stake = holder.stakes[index]; total += _computeStakeReward(stake); } total += holder.rewardDebt; } /** * Compute the reward of a single stake. * * @param stake the stake struct. * @return the token rewarded (does not include the debt). */ function _computeStakeReward(Stake storage stake) internal view returns (uint256) { uint256 numberOfDays = ((block.timestamp - stake.start) / 1 days); return (stake.amount * numberOfDays * rewardPerDay) / 1_000_000; } /** * Delete an address from the `addresses` array. * * @dev To avoid holes, the last value will replace the deleted address. * * @param index address's index to delete. */ function _deleteAddress(uint256 index) internal { uint256 length = addresses.length; require( length != 0, "Staking: cannot remove address if array length is zero" ); uint256 last = length - 1; if (last != index) { address addr = addresses[last]; addresses[index] = addr; holders[addr].index = index; } addresses.pop(); } /** * Transfer the remaining tokens back to the current contract owner and then self destruct. * * @dev This function must only be called for destruction!! * @dev If the balance is 0, the `CrunchToken#transfer(address, uint256)` is not called. */ function _transferRemainingAndSelfDestruct() internal { uint256 remaining = contractBalance(); if (remaining != 0) { crunch.transfer(owner(), remaining); } selfdestruct(payable(owner())); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "./erc677/ERC677.sol"; contract CrunchToken is ERC677, ERC20Burnable { constructor() ERC20("Crunch Token", "CRUNCH") { _mint(msg.sender, 10765163 * 10**decimals()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/access/Ownable.sol"; import "../CrunchToken.sol"; contract HasCrunchParent is Ownable { event ParentUpdated(address from, address to); CrunchToken public crunch; constructor(CrunchToken _crunch) { crunch = _crunch; emit ParentUpdated(address(0), address(crunch)); } modifier onlyCrunchParent() { require( address(crunch) == _msgSender(), "HasCrunchParent: caller is not the crunch token" ); _; } function setCrunch(CrunchToken _crunch) public onlyOwner { require(address(crunch) != address(_crunch), "useless to update to same crunch token"); emit ParentUpdated(address(crunch), address(_crunch)); crunch = _crunch; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ERC677.sol"; import "./IERC677.sol"; import "./IERC677Receiver.sol"; abstract contract ERC677 is IERC677, ERC20 { function transferAndCall( address recipient, uint256 amount, bytes memory data ) public virtual override returns (bool success) { super.transfer(recipient, amount); emit TransferAndCall(msg.sender, recipient, amount, data); if (isContract(recipient)) { IERC677Receiver receiver = IERC677Receiver(recipient); receiver.onTokenTransfer(msg.sender, amount, data); } return true; } function isContract(address addr) private view returns (bool hasCode) { uint256 length; assembly { length := extcodesize(addr) } return length > 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface IERC677 is IERC20 { /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param recipient The address to transfer to. * @param amount The amount to be transferred. * @param data The extra data to be passed to the receiving contract. */ function transferAndCall( address recipient, uint256 amount, bytes memory data ) external returns (bool success); event TransferAndCall( address indexed from, address indexed to, uint256 value, bytes data ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC677Receiver { function onTokenTransfer( address sender, uint256 value, bytes memory data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; } }
Returns the sum of the specified `addr` staked amount. addr address to check. return the total staked of the holder./
function totalStakedOf(address addr) external view returns (uint256) { return holders[addr].totalStaked; }
1,587,787
./full_match/3/0xa14B709162AE27F9c832f45469db83980c801931/sources/contracts/NounsToken.sol
Mint a Noun to the caller/ if (_currentNounId <= 1820 && _currentNounId % 10 == 0) { _mintTo(noundersDAO, _currentNounId++); }
function mint() public override returns (uint256) { return _mintTo(msg.sender, _currentNounId++); }
14,253,984
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./interfaces/IERC20.sol"; import "./libraries/SafeERC20.sol"; import "./libraries/ERC20.sol"; import "./libraries/EnumerableSet.sol"; import "./libraries/SafeMath.sol"; import "./libraries/Ownable.sol"; import "./xLessToken.sol"; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to LessSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // LessSwap must mint EXACTLY the same amount of LessSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of xLess. He can make xLess and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once xLESS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of xLESSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accXLessPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accXLessPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. xLESSs to distribute per block. uint256 lastRewardBlock; // Last block number that xLESSs distribution occurs. uint256 accXLessPerShare; // Accumulated xLESSs per share, times 1e12. See below. } // The xLESS TOKEN! xLessToken public xless; // Dev address. address public devaddr; // Block number when bonus xLESS period ends. uint256 public bonusEndBlock; // xLESS tokens created per block. uint256 public xlessPerBlock; // Bonus muliplier for early xless makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when xLESS mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( xLessToken _xless, address _devaddr, uint256 _xlessPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { xless = _xless; devaddr = _devaddr; xlessPerBlock = _xlessPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accXLessPerShare: 0 }) ); } function updateRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner { xlessPerBlock = _rewardPerBlock; } function updateStartBlock(uint256 _block) public onlyOwner { startBlock = _block; } function updateBonusEndBlock(uint256 _block) public onlyOwner { bonusEndBlock = _block; } // Update the given pool's xLESS allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending xLESSs on frontend. function pendingXLess(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accXLessPerShare = pool.accXLessPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 xlessReward = multiplier .mul(xlessPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accXLessPerShare = accXLessPerShare.add( xlessReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accXLessPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 xlessReward = multiplier .mul(xlessPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); xless.transfer(devaddr, xlessReward.div(10)); pool.accXLessPerShare = pool.accXLessPerShare.add( xlessReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for xLESS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accXLessPerShare) .div(1e12) .sub(user.rewardDebt); safeXLessTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accXLessPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accXLessPerShare).div(1e12).sub( user.rewardDebt ); safeXLessTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accXLessPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe xless transfer function, just in case if rounding error causes pool to not have enough xLESSs. function safeXLessTransfer(address _to, uint256 _amount) internal { uint256 xlessBal = xless.balanceOf(address(this)); if (_amount > xlessBal) { xless.transfer(_to, xlessBal); } else { xless.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IERC20 { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; /* * @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: GPL-3.0 pragma solidity ^0.6.12; import "./Address.sol"; import "./Context.sol"; import "./SafeMath.sol"; import "../interfaces/IERC20.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) _allowances; uint256 _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 override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 {_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 override returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage _set, bytes32 _value) internal returns (bool) { return _add(_set._inner, _value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; /** * @title Owned * @dev Basic contract for authorization control. * @author dicether */ contract Ownable { address public owner; address public pendingOwner; event LogOwnerShipTransferred( address indexed previousOwner, address indexed newOwner ); event LogOwnerShipTransferInitiated( address indexed previousOwner, address indexed newOwner ); /** * @dev Modifier, which throws if called by other account than owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Set contract creator as initial owner */ constructor() public { owner = msg.sender; pendingOwner = address(0); } /** * @dev Allows the current owner to set the pendingOwner address. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { pendingOwner = _newOwner; emit LogOwnerShipTransferInitiated(owner, _newOwner); } /** * @dev PendingOwner can accept ownership. */ function claimOwnership() public onlyPendingOwner { owner = pendingOwner; pendingOwner = address(0); emit LogOwnerShipTransferred(owner, pendingOwner); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "./Address.sol"; import "./SafeMath.sol"; import "../interfaces/IERC20.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: GPL-3.0 pragma solidity ^0.6.12; // File: @openzeppelin/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. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libraries/ERC20.sol"; import "./libraries/Ownable.sol"; // xLessToken with Governance. contract xLessToken is ERC20, Ownable { constructor() public ERC20("xLessToken", "xLESS") { _mint(msg.sender, 56000000 * (10**uint256(decimals()))); // xLess Token Initial Supply 56m } /// @dev notice A record of each accounts delegate mapping(address => address) internal _delegates; /// @dev notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @dev notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @dev notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @dev notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); /// @dev notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @dev notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @dev notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @dev notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /** * @dev notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @dev notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @dev notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "xLESS::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "xLESS::delegateBySig: invalid nonce" ); require(now <= expiry, "xLESS::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @dev notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "xLESS::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying xLESSs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32( block.number, "xLESS::_writeCheckpoint: block number exceeds 32 bits" ); if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint( blockNumber, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
notice Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "xLESS::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "xLESS::delegateBySig: invalid nonce" ); require(now <= expiry, "xLESS::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
411,646
pragma solidity ^0.4.18; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function 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; } } // ERC20 token interface is implemented only partially. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract NamiPool { using SafeMath for uint256; function NamiPool(address _escrow, address _namiMultiSigWallet, address _namiAddress) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; NamiAddr = _namiAddress; } string public name = "Nami Pool"; // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; /// address of Nami token address public NamiAddr; modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyNami { require(msg.sender == NamiAddr); _; } modifier onlyNamiMultisig { require(msg.sender == namiMultiSigWallet); _; } uint public currentRound = 1; struct ShareHolder { uint stake; bool isActive; bool isWithdrawn; } struct Round { bool isOpen; uint currentNAC; uint finalNAC; uint ethBalance; bool withdrawable; //for user not in top bool topWithdrawable; bool isCompleteActive; bool isCloseEthPool; } mapping (uint => mapping (address => ShareHolder)) public namiPool; mapping (uint => Round) public round; // Events event UpdateShareHolder(address indexed ShareHolderAddress, uint indexed RoundIndex, uint Stake, uint Time); event Deposit(address sender,uint indexed RoundIndex, uint value); event WithdrawPool(uint Amount, uint TimeWithdraw); event UpdateActive(address indexed ShareHolderAddress, uint indexed RoundIndex, bool Status, uint Time); event Withdraw(address indexed ShareHolderAddress, uint indexed RoundIndex, uint Ether, uint Nac, uint TimeWithdraw); event ActivateRound(uint RoundIndex, uint TimeActive); function changeEscrow(address _escrow) onlyNamiMultisig public { require(_escrow != 0x0); escrow = _escrow; } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } function withdrawNAC(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0 && _amount != 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); if (namiToken.balanceOf(this) > 0) { namiToken.transfer(namiMultiSigWallet, _amount); } } /*/ * Admin function /*/ /*/ process of one round * step 1: admin open one round by execute activateRound function * step 2: now investor can invest Nac to Nac Pool until round closed * step 3: admin close round, now investor cann&#39;t invest NAC to Pool * step 4: admin activate top investor * step 5: all top investor was activated, admin execute closeActive function to close active phrase * step 6: admin open withdrawable for investor not in top to withdraw NAC * step 7: admin deposit eth to eth pool * step 8: close deposit eth to eth pool * step 9: admin open withdrawable to investor in top * step 10: investor in top now can withdraw NAC and ETH for this round /*/ // ------------------------------------------------ /* * Admin function * Open and Close Round * */ function activateRound(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isOpen == false && round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isCompleteActive == false); round[_roundIndex].isOpen = true; currentRound = _roundIndex; ActivateRound(_roundIndex, now); } function deactivateRound(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isOpen == true); round[_roundIndex].isOpen = false; } // ------------------------------------------------ // this function add stake of ShareHolder // investor can execute this function during round open // function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) { // only on currentRound and active user can add stake require(round[_price].isOpen == true && _value > 0); // add stake namiPool[_price][_from].stake = namiPool[_price][_from].stake.add(_value); round[_price].currentNAC = round[_price].currentNAC.add(_value); UpdateShareHolder(_from, _price, namiPool[_price][_from].stake, now); return true; } /* * * Activate and deactivate user * add or sub final Nac to compute stake to withdraw */ function activateUser(address _shareAddress, uint _roundId) onlyEscrow public { require(namiPool[_roundId][_shareAddress].isActive == false && namiPool[_roundId][_shareAddress].stake > 0); require(round[_roundId].isCompleteActive == false && round[_roundId].isOpen == false); namiPool[_roundId][_shareAddress].isActive = true; round[_roundId].finalNAC = round[_roundId].finalNAC.add(namiPool[_roundId][_shareAddress].stake); UpdateActive(_shareAddress, _roundId ,namiPool[_roundId][_shareAddress].isActive, now); } function deactivateUser(address _shareAddress, uint _roundId) onlyEscrow public { require(namiPool[_roundId][_shareAddress].isActive == true && namiPool[_roundId][_shareAddress].stake > 0); require(round[_roundId].isCompleteActive == false && round[_roundId].isOpen == false); namiPool[_roundId][_shareAddress].isActive = false; round[_roundId].finalNAC = round[_roundId].finalNAC.sub(namiPool[_roundId][_shareAddress].stake); UpdateActive(_shareAddress, _roundId ,namiPool[_roundId][_shareAddress].isActive, now); } // ------------------------------------------------ // admin close activate phrase to // // function closeActive(uint _roundId) onlyEscrow public { require(round[_roundId].isCompleteActive == false && round[_roundId].isOpen == false); round[_roundId].isCompleteActive = true; } // // // change Withdrawable for one round after every month // for investor not in top // function changeWithdrawable(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); round[_roundIndex].withdrawable = !round[_roundIndex].withdrawable; } // // // change Withdrawable for one round after every month // for investor in top // function changeTopWithdrawable(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); round[_roundIndex].topWithdrawable = !round[_roundIndex].topWithdrawable; } // // // after month admin deposit ETH to ETH Pool // // function depositEthPool(uint _roundIndex) payable public onlyEscrow { require(msg.value > 0 && round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isOpen == false); if (msg.value > 0) { round[_roundIndex].ethBalance = round[_roundIndex].ethBalance.add(msg.value); Deposit(msg.sender, _roundIndex, msg.value); } } // // function withdrawEthPool(uint _roundIndex, uint _amount) public onlyEscrow { require(round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isOpen == false); require(namiMultiSigWallet != 0x0); // if (_amount > 0) { namiMultiSigWallet.transfer(_amount); round[_roundIndex].ethBalance = round[_roundIndex].ethBalance.sub(_amount); WithdrawPool(_amount, now); } } // // close phrase deposit ETH to Pool // function closeEthPool(uint _roundIndex) public onlyEscrow { require(round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); round[_roundIndex].isCloseEthPool = true; } // // // withdraw NAC for investor // internal function only can run by this smartcontract // // function _withdrawNAC(address _shareAddress, uint _roundIndex) internal { require(namiPool[_roundIndex][_shareAddress].stake > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(this); namiToken.transfer(_shareAddress, namiPool[_roundIndex][_shareAddress].stake); // update current Nac pool balance round[_roundIndex].currentNAC = round[_roundIndex].currentNAC.sub(namiPool[_roundIndex][_shareAddress].stake); namiPool[_roundIndex][_shareAddress].stake = 0; assert(previousBalances > namiToken.balanceOf(this)); } // // // withdraw NAC and ETH for top investor // // function withdrawTopForTeam(address _shareAddress, uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isCloseEthPool == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].topWithdrawable); if(namiPool[_roundIndex][_shareAddress].isActive == true) { require(namiPool[_roundIndex][_shareAddress].isWithdrawn == false); assert(round[_roundIndex].finalNAC > namiPool[_roundIndex][_shareAddress].stake); // compute eth for invester uint ethReturn = (round[_roundIndex].ethBalance.mul(namiPool[_roundIndex][_shareAddress].stake)).div(round[_roundIndex].finalNAC); _shareAddress.transfer(ethReturn); // set user withdraw namiPool[_roundIndex][_shareAddress].isWithdrawn = true; Withdraw(_shareAddress, _roundIndex, ethReturn, namiPool[_roundIndex][_shareAddress].stake, now); // withdraw NAC _withdrawNAC(_shareAddress, _roundIndex); } } // // // withdraw NAC and ETH for non top investor // execute by admin only // // function withdrawNonTopForTeam(address _shareAddress, uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].withdrawable); if(namiPool[_roundIndex][_shareAddress].isActive == false) { require(namiPool[_roundIndex][_shareAddress].isWithdrawn == false); // set state user withdraw namiPool[_roundIndex][_shareAddress].isWithdrawn = true; Withdraw(_shareAddress, _roundIndex, 0, namiPool[_roundIndex][_shareAddress].stake, now); // _withdrawNAC(_shareAddress, _roundIndex); } } // // // withdraw NAC and ETH for top investor // execute by investor // // function withdrawTop(uint _roundIndex) public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isCloseEthPool == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].topWithdrawable); if(namiPool[_roundIndex][msg.sender].isActive == true) { require(namiPool[_roundIndex][msg.sender].isWithdrawn == false); uint ethReturn = (round[_roundIndex].ethBalance.mul(namiPool[_roundIndex][msg.sender].stake)).div(round[_roundIndex].finalNAC); msg.sender.transfer(ethReturn); // set user withdraw namiPool[_roundIndex][msg.sender].isWithdrawn = true; // Withdraw(msg.sender, _roundIndex, ethReturn, namiPool[_roundIndex][msg.sender].stake, now); _withdrawNAC(msg.sender, _roundIndex); } } // // // withdraw NAC and ETH for non top investor // execute by investor // // function withdrawNonTop(uint _roundIndex) public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].withdrawable); if(namiPool[_roundIndex][msg.sender].isActive == false) { require(namiPool[_roundIndex][msg.sender].isWithdrawn == false); namiPool[_roundIndex][msg.sender].isWithdrawn = true; // Withdraw(msg.sender, _roundIndex, 0, namiPool[_roundIndex][msg.sender].stake, now); _withdrawNAC(msg.sender, _roundIndex); } } } contract NamiCrowdSale { using SafeMath for uint256; /// NAC Broker Presale Token /// @dev Constructor function NamiCrowdSale(address _escrow, address _namiMultiSigWallet, address _namiPresale) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; namiPresale = _namiPresale; } /*/ * Constants /*/ string public name = "Nami ICO"; string public symbol = "NAC"; uint public decimals = 18; bool public TRANSFERABLE = false; // default not transferable uint public constant TOKEN_SUPPLY_LIMIT = 1000000000 * (1 ether / 1 wei); uint public binary = 0; /*/ * Token state /*/ enum Phase { Created, Running, Paused, Migrating, Migrated } Phase public currentPhase = Phase.Created; uint public totalSupply = 0; // amount of tokens already sold // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; // nami presale contract address public namiPresale; // Crowdsale manager has exclusive priveleges to burn presale tokens. address public crowdsaleManager; // binary option address address public binaryAddress; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; modifier onlyCrowdsaleManager() { require(msg.sender == crowdsaleManager); _; } modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyTranferable() { require(TRANSFERABLE); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } /*/ * Events /*/ event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); event LogPhaseSwitch(Phase newPhase); // Log migrate token event LogMigrate(address _from, address _to, uint256 amount); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /*/ * Public functions /*/ /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } // Transfer the balance from owner&#39;s account to another account // only escrow can send token (to send token private sale) function transferForTeam(address _to, uint256 _value) public onlyEscrow { _transfer(msg.sender, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public onlyTranferable { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public onlyTranferable returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public onlyTranferable returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyTranferable returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } // allows transfer token function changeTransferable () public onlyEscrow { TRANSFERABLE = !TRANSFERABLE; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // change binary value function changeBinary(uint _binary) public onlyEscrow { binary = _binary; } // change binary address function changeBinaryAddress(address _binaryAddress) public onlyEscrow { require(_binaryAddress != 0x0); binaryAddress = _binaryAddress; } /* * price in ICO: * first week: 1 ETH = 2400 NAC * second week: 1 ETH = 23000 NAC * 3rd week: 1 ETH = 2200 NAC * 4th week: 1 ETH = 2100 NAC * 5th week: 1 ETH = 2000 NAC * 6th week: 1 ETH = 1900 NAC * 7th week: 1 ETH = 1800 NAC * 8th week: 1 ETH = 1700 nac * time: * 1517443200: Thursday, February 1, 2018 12:00:00 AM * 1518048000: Thursday, February 8, 2018 12:00:00 AM * 1518652800: Thursday, February 15, 2018 12:00:00 AM * 1519257600: Thursday, February 22, 2018 12:00:00 AM * 1519862400: Thursday, March 1, 2018 12:00:00 AM * 1520467200: Thursday, March 8, 2018 12:00:00 AM * 1521072000: Thursday, March 15, 2018 12:00:00 AM * 1521676800: Thursday, March 22, 2018 12:00:00 AM * 1522281600: Thursday, March 29, 2018 12:00:00 AM */ function getPrice() public view returns (uint price) { if (now < 1517443200) { // presale return 3450; } else if (1517443200 < now && now <= 1518048000) { // 1st week return 2400; } else if (1518048000 < now && now <= 1518652800) { // 2nd week return 2300; } else if (1518652800 < now && now <= 1519257600) { // 3rd week return 2200; } else if (1519257600 < now && now <= 1519862400) { // 4th week return 2100; } else if (1519862400 < now && now <= 1520467200) { // 5th week return 2000; } else if (1520467200 < now && now <= 1521072000) { // 6th week return 1900; } else if (1521072000 < now && now <= 1521676800) { // 7th week return 1800; } else if (1521676800 < now && now <= 1522281600) { // 8th week return 1700; } else { return binary; } } function() payable public { buy(msg.sender); } function buy(address _buyer) payable public { // Available only if presale is running. require(currentPhase == Phase.Running); // require ICO time or binary option require(now <= 1522281600 || msg.sender == binaryAddress); require(msg.value != 0); uint newTokens = msg.value * getPrice(); require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT); // add new token to buyer balanceOf[_buyer] = balanceOf[_buyer].add(newTokens); // add new token to totalSupply totalSupply = totalSupply.add(newTokens); LogBuy(_buyer,newTokens); Transfer(this,_buyer,newTokens); } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function burnTokens(address _owner) public onlyCrowdsaleManager { // Available only during migration phase require(currentPhase == Phase.Migrating); uint tokens = balanceOf[_owner]; require(tokens != 0); balanceOf[_owner] = 0; totalSupply -= tokens; LogBurn(_owner, tokens); Transfer(_owner, crowdsaleManager, tokens); // Automatically switch phase when migration is done. if (totalSupply == 0) { currentPhase = Phase.Migrated; LogPhaseSwitch(Phase.Migrated); } } /*/ * Administrative functions /*/ function setPresalePhase(Phase _nextPhase) public onlyEscrow { bool canSwitchPhase = (currentPhase == Phase.Created && _nextPhase == Phase.Running) || (currentPhase == Phase.Running && _nextPhase == Phase.Paused) // switch to migration phase only if crowdsale manager is set || ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running) // switch to migrated only if everyting is migrated || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated && totalSupply == 0); require(canSwitchPhase); currentPhase = _nextPhase; LogPhaseSwitch(_nextPhase); } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } function setCrowdsaleManager(address _mgr) public onlyEscrow { // You can&#39;t change crowdsale contract when migration is in progress. require(currentPhase != Phase.Migrating); crowdsaleManager = _mgr; } // internal migrate migration tokens function _migrateToken(address _from, address _to) internal { PresaleToken presale = PresaleToken(namiPresale); uint256 newToken = presale.balanceOf(_from); require(newToken > 0); // burn old token presale.burnTokens(_from); // add new token to _to balanceOf[_to] = balanceOf[_to].add(newToken); // add new token to totalSupply totalSupply = totalSupply.add(newToken); LogMigrate(_from, _to, newToken); Transfer(this,_to,newToken); } // migate token function for Nami Team function migrateToken(address _from, address _to) public onlyEscrow { _migrateToken(_from, _to); } // migrate token for investor function migrateForInvestor() public { _migrateToken(msg.sender, msg.sender); } // Nami internal exchange // event for Nami exchange event TransferToBuyer(address indexed _from, address indexed _to, uint _value, address indexed _seller); event TransferToExchange(address indexed _from, address indexed _to, uint _value, uint _price); /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackExchange` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackExchange` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _price price to sell token. */ function transferToExchange(address _to, uint _value, uint _price) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackExchange(msg.sender, _value, _price); TransferToExchange(msg.sender, _to, _value, _price); } } /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackBuyer` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackBuyer` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _buyer address of seller. */ function transferToBuyer(address _to, uint _value, address _buyer) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackBuyer(msg.sender, _value, _buyer); TransferToBuyer(msg.sender, _to, _value, _buyer); } } //------------------------------------------------------------------------------------------------------- } /* * Binary option smart contract------------------------------- */ contract BinaryOption { /* * binary option controled by escrow to buy NAC with good price */ // NamiCrowdSale address address public namiCrowdSaleAddr; address public escrow; // namiMultiSigWallet address public namiMultiSigWallet; Session public session; uint public timeInvestInMinute = 15; uint public timeOneSession = 20; uint public sessionId = 1; uint public rateWin = 100; uint public rateLoss = 20; uint public rateFee = 5; uint public constant MAX_INVESTOR = 20; uint public minimunEth = 10000000000000000; // minimunEth = 0.01 eth /** * Events for binany option system */ event SessionOpen(uint timeOpen, uint indexed sessionId); event InvestClose(uint timeInvestClose, uint priceOpen, uint indexed sessionId); event Invest(address indexed investor, bool choose, uint amount, uint timeInvest, uint indexed sessionId); event SessionClose(uint timeClose, uint indexed sessionId, uint priceClose, uint nacPrice, uint rateWin, uint rateLoss, uint rateFee); event Deposit(address indexed sender, uint value); /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } // there is only one session available at one timeOpen // priceOpen is price of ETH in USD // priceClose is price of ETH in USD // process of one Session // 1st: escrow reset session by run resetSession() // 2nd: escrow open session by run openSession() => save timeOpen at this time // 3rd: all investor can invest by run invest(), send minimum 0.1 ETH // 4th: escrow close invest and insert price open for this Session // 5th: escrow close session and send NAC for investor struct Session { uint priceOpen; uint priceClose; uint timeOpen; bool isReset; bool isOpen; bool investOpen; uint investorCount; mapping(uint => address) investor; mapping(uint => bool) win; mapping(uint => uint) amountInvest; } function BinaryOption(address _namiCrowdSale, address _escrow, address _namiMultiSigWallet) public { require(_namiCrowdSale != 0x0 && _escrow != 0x0); namiCrowdSaleAddr = _namiCrowdSale; escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; } modifier onlyEscrow() { require(msg.sender==escrow); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // chagne minimunEth function changeMinEth(uint _minimunEth) public onlyEscrow { require(_minimunEth != 0); minimunEth = _minimunEth; } /// @dev Change time for investor can invest in one session, can only change at time not in session /// @param _timeInvest time invest in minutes ///---------------------------change time function------------------------------ function changeTimeInvest(uint _timeInvest) public onlyEscrow { require(!session.isOpen && _timeInvest < timeOneSession); timeInvestInMinute = _timeInvest; } function changeTimeOneSession(uint _timeOneSession) public onlyEscrow { require(!session.isOpen && _timeOneSession > timeInvestInMinute); timeOneSession = _timeOneSession; } /////------------------------change rate function------------------------------- function changeRateWin(uint _rateWin) public onlyEscrow { require(!session.isOpen); rateWin = _rateWin; } function changeRateLoss(uint _rateLoss) public onlyEscrow { require(!session.isOpen); rateLoss = _rateLoss; } function changeRateFee(uint _rateFee) public onlyEscrow { require(!session.isOpen); rateFee = _rateFee; } /// @dev withdraw ether to nami multisignature wallet, only escrow can call /// @param _amount value ether in wei to withdraw function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } /// @dev safe withdraw Ether to one of owner of nami multisignature wallet /// @param _withdraw address to withdraw function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } // @dev Returns list of owners. // @return List of owner addresses. // MAX_INVESTOR = 20 function getInvestors() public view returns (address[20]) { address[20] memory listInvestor; for (uint i = 0; i < MAX_INVESTOR; i++) { listInvestor[i] = session.investor[i]; } return listInvestor; } function getChooses() public view returns (bool[20]) { bool[20] memory listChooses; for (uint i = 0; i < MAX_INVESTOR; i++) { listChooses[i] = session.win[i]; } return listChooses; } function getAmount() public view returns (uint[20]) { uint[20] memory listAmount; for (uint i = 0; i < MAX_INVESTOR; i++) { listAmount[i] = session.amountInvest[i]; } return listAmount; } /// @dev reset all data of previous session, must run before open new session // only escrow can call function resetSession() public onlyEscrow { require(!session.isReset && !session.isOpen); session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.isOpen = false; session.investOpen = false; session.investorCount = 0; for (uint i = 0; i < MAX_INVESTOR; i++) { session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } } /// @dev Open new session, only escrow can call function openSession () public onlyEscrow { require(session.isReset && !session.isOpen); session.isReset = false; // open invest session.investOpen = true; session.timeOpen = now; session.isOpen = true; SessionOpen(now, sessionId); } /// @dev Fuction for investor, minimun ether send is 0.1, one address can call one time in one session /// @param _choose choise of investor, true is call, false is put function invest (bool _choose) public payable { require(msg.value >= minimunEth && session.investOpen); // msg.value >= 0.1 ether require(now < (session.timeOpen + timeInvestInMinute * 1 minutes)); require(session.investorCount < MAX_INVESTOR); session.investor[session.investorCount] = msg.sender; session.win[session.investorCount] = _choose; session.amountInvest[session.investorCount] = msg.value; session.investorCount += 1; Invest(msg.sender, _choose, msg.value, now, sessionId); } /// @dev close invest for escrow /// @param _priceOpen price ETH in USD function closeInvest (uint _priceOpen) public onlyEscrow { require(_priceOpen != 0 && session.investOpen); require(now > (session.timeOpen + timeInvestInMinute * 1 minutes)); session.investOpen = false; session.priceOpen = _priceOpen; InvestClose(now, _priceOpen, sessionId); } /// @dev get amount of ether to buy NAC for investor /// @param _ether amount ether which investor invest /// @param _status true for investor win and false for investor loss function getEtherToBuy (uint _ether, bool _status) public view returns (uint) { if (_status) { return _ether * rateWin / 100; } else { return _ether * rateLoss / 100; } } /// @dev close session, only escrow can call /// @param _priceClose price of ETH in USD function closeSession (uint _priceClose) public onlyEscrow { require(_priceClose != 0 && now > (session.timeOpen + timeOneSession * 1 minutes)); require(!session.investOpen && session.isOpen); session.priceClose = _priceClose; bool result = (_priceClose>session.priceOpen)?true:false; uint etherToBuy; NamiCrowdSale namiContract = NamiCrowdSale(namiCrowdSaleAddr); uint price = namiContract.getPrice(); require(price != 0); for (uint i = 0; i < session.investorCount; i++) { if (session.win[i]==result) { etherToBuy = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateWin / 100; uint etherReturn = session.amountInvest[i] - session.amountInvest[i] * rateFee / 100; (session.investor[i]).transfer(etherReturn); } else { etherToBuy = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateLoss / 100; } namiContract.buy.value(etherToBuy)(session.investor[i]); // reset investor session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } session.isOpen = false; SessionClose(now, sessionId, _priceClose, price, rateWin, rateLoss, rateFee); sessionId += 1; // require(!session.isReset && !session.isOpen); // reset state session session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.investOpen = false; session.investorCount = 0; } } contract PresaleToken { mapping (address => uint256) public balanceOf; function burnTokens(address _owner) public; } /* * Contract that is working with ERC223 tokens */ /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public returns (bool success); function tokenFallbackBuyer(address _from, uint _value, address _buyer) public returns (bool success); function tokenFallbackExchange(address _from, uint _value, uint _price) public returns (bool success); } /* * Nami Internal Exchange smartcontract----------------------------------------------------------------- * */ contract NamiExchange { using SafeMath for uint; function NamiExchange(address _namiAddress) public { NamiAddr = _namiAddress; } event UpdateBid(address owner, uint price, uint balance); event UpdateAsk(address owner, uint price, uint volume); event BuyHistory(address indexed buyer, address indexed seller, uint price, uint volume, uint time); event SellHistory(address indexed seller, address indexed buyer, uint price, uint volume, uint time); mapping(address => OrderBid) public bid; mapping(address => OrderAsk) public ask; string public name = "NacExchange"; /// address of Nami token address public NamiAddr; /// price of Nac = ETH/NAC uint public price = 1; // struct store order of user struct OrderBid { uint price; uint eth; } struct OrderAsk { uint price; uint volume; } // prevent lost ether function() payable public { require(msg.data.length != 0); require(msg.value == 0); } modifier onlyNami { require(msg.sender == NamiAddr); _; } ///////////////// //---------------------------function about bid Order----------------------------------------------------------- function placeBuyOrder(uint _price) payable public { require(_price > 0 && msg.value > 0 && bid[msg.sender].eth == 0); if (msg.value > 0) { bid[msg.sender].eth = (bid[msg.sender].eth).add(msg.value); bid[msg.sender].price = _price; UpdateBid(msg.sender, _price, bid[msg.sender].eth); } } function sellNac(uint _value, address _buyer, uint _price) public returns (bool success) { require(_price == bid[_buyer].price && _buyer != msg.sender); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint ethOfBuyer = bid[_buyer].eth; uint maxToken = ethOfBuyer.mul(bid[_buyer].price); require(namiToken.allowance(msg.sender, this) >= _value && _value > 0 && ethOfBuyer != 0 && _buyer != 0x0); if (_value > maxToken) { if (msg.sender.send(ethOfBuyer) && namiToken.transferFrom(msg.sender,_buyer,maxToken)) { // update order bid[_buyer].eth = 0; UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); BuyHistory(_buyer, msg.sender, bid[_buyer].price, maxToken, now); return true; } else { // revert anything revert(); } } else { uint eth = _value.div(bid[_buyer].price); if (msg.sender.send(eth) && namiToken.transferFrom(msg.sender,_buyer,_value)) { // update order bid[_buyer].eth = (bid[_buyer].eth).sub(eth); UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); BuyHistory(_buyer, msg.sender, bid[_buyer].price, _value, now); return true; } else { // revert anything revert(); } } } function closeBidOrder() public { require(bid[msg.sender].eth > 0 && bid[msg.sender].price > 0); // transfer ETH msg.sender.transfer(bid[msg.sender].eth); // update order bid[msg.sender].eth = 0; UpdateBid(msg.sender, bid[msg.sender].price, bid[msg.sender].eth); } //////////////// //---------------------------function about ask Order----------------------------------------------------------- // place ask order by send NAC to Nami Exchange contract // this function place sell order function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) { require(_price > 0 && _value > 0 && ask[_from].volume == 0); if (_value > 0) { ask[_from].volume = (ask[_from].volume).add(_value); ask[_from].price = _price; UpdateAsk(_from, _price, ask[_from].volume); } return true; } function closeAskOrder() public { require(ask[msg.sender].volume > 0 && ask[msg.sender].price > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(msg.sender); // transfer token namiToken.transfer(msg.sender, ask[msg.sender].volume); // update order ask[msg.sender].volume = 0; UpdateAsk(msg.sender, ask[msg.sender].price, 0); // check balance assert(previousBalances < namiToken.balanceOf(msg.sender)); } function buyNac(address _seller, uint _price) payable public returns (bool success) { require(msg.value > 0 && ask[_seller].volume > 0 && ask[_seller].price > 0); require(_price == ask[_seller].price && _seller != msg.sender); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint maxEth = (ask[_seller].volume).div(ask[_seller].price); uint previousBalances = namiToken.balanceOf(msg.sender); if (msg.value > maxEth) { if (_seller.send(maxEth) && msg.sender.send(msg.value.sub(maxEth))) { // transfer token namiToken.transfer(msg.sender, ask[_seller].volume); SellHistory(_seller, msg.sender, ask[_seller].price, ask[_seller].volume, now); // update order ask[_seller].volume = 0; UpdateAsk(_seller, ask[_seller].price, 0); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } else { uint nac = (msg.value).mul(ask[_seller].price); if (_seller.send(msg.value)) { // transfer token namiToken.transfer(msg.sender, nac); // update order ask[_seller].volume = (ask[_seller].volume).sub(nac); UpdateAsk(_seller, ask[_seller].price, ask[_seller].volume); SellHistory(_seller, msg.sender, ask[_seller].price, nac, now); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } } } contract ERC23 { function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public returns (bool success); } /* * NamiMultiSigWallet smart contract------------------------------- */ /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. contract NamiMultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(!(ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0)); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function NamiMultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { // Transaction tx = transactions[transactionId]; transactions[transactionId].executed = true; // tx.executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) { Execution(transactionId); } else { ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } } }
Allows to replace an owner with a new owner. Transaction has to be sent by wallet. owner Address of owner to be replaced. owner Address of new owner.
function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); }
7,874,051
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./Badger.sol"; contract Karmic is Badger, Pausable { uint256 public constant FEE_PRECISION = 1 ether; // 10^18 = 100% uint256 public constant TOKENS_PER_ETH = 1000; mapping(address => BoxToken) public boxTokenTiers; uint256 public boxTokenCounter; uint256 public fee; struct BoxToken { uint256 id; uint256 amount; uint256 funds; uint256 distributed; bool passedThreshold; uint256 threshold; } event FundsDistributed( address indexed receiver, uint256 indexed tokenTier, uint256 amount ); modifier isBoxToken(address token) { require(boxTokenTiers[token].id != 0, "It is not a box token"); _; } constructor(string memory _newBaseUri, string memory _metadata, uint256 _fee) Badger(_newBaseUri) { boxTokenCounter = 1; fee = _fee; createTokenTier(0, _metadata, false, address(0)); } function setFee(uint256 _fee) external onlyOwner { fee = _fee; } function bondToMint(address token, uint256 amount) public whenNotPaused isBoxToken(token) { require(IERC20(token).transferFrom(msg.sender, address(this), amount), "transfer failed"); bytes memory data; _mint(msg.sender, boxTokenTiers[token].id, amount/TOKENS_PER_ETH, data); } function addBoxTokens( address[] memory tokens, string[] calldata tierUris, uint256[] calldata threshold ) external onlyOwner { uint256 counter = boxTokenCounter; for (uint8 i; i < tokens.length; i++) { address token = tokens[i]; require(boxTokenTiers[token].id == 0, "DUPLICATE_TOKEN"); boxTokenTiers[token].id = counter; boxTokenTiers[token].threshold = threshold[i]; createTokenTier(counter, tierUris[i], false, token); counter++; } boxTokenCounter = counter; } function withdraw(address token, uint256 amount) external whenNotPaused isBoxToken(token) { uint256 totalFunding = (boxTokenTiers[token].funds*FEE_PRECISION) / (FEE_PRECISION - fee); require( !(totalFunding >= boxTokenTiers[token].threshold), "Can withdraw only funds for tokens that didn't pass threshold" ); uint256 withdrawnFunds = (amount * totalFunding) / boxTokenTiers[token].amount; boxTokenTiers[token].funds -= withdrawnFunds - withdrawnFunds*fee/FEE_PRECISION; boxTokenTiers[address(0)].funds -= withdrawnFunds*fee/FEE_PRECISION; require(IERC20(token).transferFrom(msg.sender, address(this), amount), "transfer failed"); Address.sendValue(payable(msg.sender), withdrawnFunds); } function claimGovernanceTokens(address[] memory boxTokens) external whenNotPaused { bytes memory data; address token; for (uint8 i; i < boxTokens.length; i++) { token = boxTokens[i]; uint256 amount = IERC20(token).balanceOf(msg.sender); uint256 tokenId = boxTokenTiers[token].id; require(tokenId != 0, "It is not a box token"); require(IERC20(token).transferFrom(msg.sender, address(this), amount), "transfer failed"); _mint(msg.sender, tokenId, amount/TOKENS_PER_ETH, data); } } function distribute( address payable _receiver, uint256 _tier, uint256 _amount ) external onlyOwner { BoxToken storage boxToken = boxTokenTiers[tokenTiers[_tier].boxToken]; require(_amount != 0, "nothing to distribute"); require( boxToken.funds - boxToken.distributed >= _amount, "exceeds balance" ); boxToken.distributed += _amount; Address.sendValue(_receiver, _amount); emit FundsDistributed(_receiver, _tier, _amount); } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function getBoxTokens() public view returns (address[] memory boxTokens) { boxTokens = new address[](boxTokenCounter); for (uint8 i = 1; i <= boxTokenCounter; i++) { boxTokens[i - 1] = tokenTiers[i].boxToken; } } function allBalancesOf(address holder) external view returns (uint256[] memory balances) { balances = new uint256[](boxTokenCounter); for (uint8 i; i < boxTokenCounter; i++) { balances[i] = balanceOf(holder, i); } } receive() external whenNotPaused payable { if (boxTokenTiers[msg.sender].id != 0) { boxTokenTiers[msg.sender].amount = IERC20(msg.sender).totalSupply(); boxTokenTiers[msg.sender].funds += msg.value - (msg.value*fee/FEE_PRECISION); boxTokenTiers[address(0)].funds += (msg.value*fee/FEE_PRECISION); } else { bytes memory data; boxTokenTiers[address(0)].funds += msg.value; _mint(msg.sender, 0, msg.value, data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/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() { _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()); } } // SPDX-License-Identifier: GPL-3.0-or-later // Badger is a ERC1155 token used for governance. pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./libraries/Strings.sol"; contract Badger is Ownable, ERC1155 { using Strings for string; /* State variables */ mapping(uint256 => TokenTier) public tokenTiers; // tokenId => TokenTier /* Structs */ struct TokenTier { string uriId; bool transferable; address boxToken; } /* Events */ event TierChange(uint256 indexed tokenId, string uriId, bool transferables); /* Modifiers */ modifier isSameLength( address[] calldata accounts, uint256[] calldata tokenIds, uint256[] memory amounts ) { require( accounts.length == tokenIds.length && tokenIds.length == amounts.length, "Input array mismatch" ); _; } modifier isTier(uint256 tokenId) { require( !_isEmptyString(tokenTiers[tokenId].uriId), "Tier does not exist" ); _; } modifier isValidString(string memory uriId) { require(!_isEmptyString(uriId), "String cannot be empty"); _; } modifier onlyGeneralToken(uint256 id) { require( tokenTiers[id].boxToken == address(0), "only on general tokens" ); _; } /* Constructor */ constructor(string memory _newBaseUri) ERC1155(_newBaseUri) {} /* Minting & burning */ /** * @dev mints specified amount token(s) of specific id to specified account * @param account beneficiary address * @param id id of token, aka. tier * @param amount units of token to be minted to beneficiary */ function mint( address account, uint256 id, uint256 amount ) public onlyOwner onlyGeneralToken(id) { bytes memory data; _mint(account, id, amount, data); } /** * @dev burns specified amount token(s) of specific id from specified account * @param account address of token holder * @param id id of token, aka. tier * @param amount units of token to be burnt from beneficiary */ function burn( address account, uint256 id, uint256 amount ) public onlyOwner onlyGeneralToken(id) { _burn(account, id, amount); } /** * @dev mints to multiple addresses arbitrary units of tokens of ONE token id per address * @notice example: mint 3 units of tokenId 1 to alice and 4 units of tokenId 2 to bob * @param accounts list of beneficiary addresses * @param tokenIds list of token ids (aka tiers) * @param amounts list of mint amounts */ function mintToMultiple( address[] calldata accounts, uint256[] calldata tokenIds, uint256[] calldata amounts ) public onlyOwner isSameLength(accounts, tokenIds, amounts) { bytes memory data; for (uint256 i = 0; i < accounts.length; i++) { require( tokenTiers[tokenIds[i]].boxToken == address(0), "Can mint only general tokens" ); _mint(accounts[i], tokenIds[i], amounts[i], data); } } /** * @dev burns from multiple addresses arbitrary units of tokens of ONE token id per address * example: burn 3 units of tokenId 1 from alice and 4 units of tokenId 2 froms bob * @param accounts list of token holder addresses * @param tokenIds list of token ids (aka tiers) * @param amounts list of burn amounts */ function burnFromMultiple( address[] calldata accounts, uint256[] calldata tokenIds, uint256[] calldata amounts ) public onlyOwner isSameLength(accounts, tokenIds, amounts) { for (uint256 i = 0; i < accounts.length; i++) { require( tokenTiers[tokenIds[i]].boxToken == address(0), "Can burn only general tokens" ); _burn(accounts[i], tokenIds[i], amounts[i]); } } /* Transferring */ /** * @dev transfers tokens from one address to another and uses 0x0 as default data parameter * @notice this is mainly used for manual contract interactions via etherscan * @param from address from which token will be transferred * @param to recipient of address * @param id id of token to be transferred * @param amount amount of token to be transferred */ function transferFromWithoutData( address from, address to, uint256 id, uint256 amount ) public { bytes memory data; _safeTransferFrom(from, to, id, amount, data); } /** * @dev transfers tokens from one address to another allowing custom data parameter * @notice this is the standard transfer interface for ERC1155 tokens which contracts expect * @param from address from which token will be transferred * @param to recipient of address * @param id id of token to be transferred * @param amount amount of token to be transferred */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public override { require( owner() == _msgSender() || from == _msgSender() || isApprovedForAll(from, _msgSender()), "Unauthorized" ); _safeTransferFrom(from, to, id, amount, data); } /* Configuration */ /** * @dev sets a base uri, that is the first part of the url where the metadata for a tokenId is stored * @param _newBaseUri baseUrl (e.g. www.filestoring.com/) */ function changeBaseUri(string calldata _newBaseUri) public onlyOwner isValidString(_newBaseUri) { _setURI(_newBaseUri); } /** * @dev creates a new token tier * @param tokenId identifier for the new token tier * @param uriId identifier that is appended to the baseUri together forming the uri where the metadata lives * @param transferable determines if tokens from specific tier should be transferable or not */ function createTokenTier( uint256 tokenId, string memory uriId, bool transferable, address boxToken ) public onlyOwner isValidString(uriId) { require( _isEmptyString(tokenTiers[tokenId].uriId), "Tier already exists for tokenId" ); tokenTiers[tokenId] = TokenTier(uriId, transferable, boxToken); emit TierChange(tokenId, uriId, transferable); } /** * @dev updates the identifier that is appended to the baseUri for a specific tokenId (tier) * @param tokenId tokenId for which the uri should be updated * @param uriId identifier that is appended to the baseUri together forming the uri where the metadata lives */ function updateUriIdentifier(uint256 tokenId, string calldata uriId) public onlyOwner { _updateUriIdentifier(tokenId, uriId); } /** * @dev update uri identifiers for multiple token ids (tiers) * @param tokenIds tokenIds for which the uri should be updated (must be in same order as uriIds) * @param uriIds identifiers that are appended to the baseUri together forming the uri where the metadata lives (must be in same order ass tokenIds) */ function updateMultipleUriIdentifiers( uint256[] calldata tokenIds, string[] calldata uriIds ) public onlyOwner { require(tokenIds.length == uriIds.length, "Input array mismatch"); for (uint8 i = 0; i < tokenIds.length; i++) { _updateUriIdentifier(tokenIds[i], uriIds[i]); } } /** * @dev updates transferability for a given token id (tier) * @param tokenId tokenId for which transferability should be updated * @param transferable determines whether tokens from tier should be transferable or not */ function updateTransferableStatus(uint256 tokenId, bool transferable) public onlyOwner isTier(tokenId) { tokenTiers[tokenId].transferable = transferable; emit TierChange(tokenId, tokenTiers[tokenId].uriId, transferable); } /* Queries */ /** * @dev returns the uri for a given token * @notice consists of a concatenation of baseUri and uriId * @param tokenId tokenId for which the uri should be retrieved */ function uri(uint256 tokenId) public view virtual override returns (string memory) { string memory baseUri = super.uri(tokenId); return baseUri.append(tokenTiers[tokenId].uriId); } /* Internal functions */ function _updateUriIdentifier(uint256 tokenId, string calldata uriId) private isTier(tokenId) isValidString(uriId) { tokenTiers[tokenId].uriId = uriId; emit TierChange(tokenId, uriId, tokenTiers[tokenId].transferable); } function _isEmptyString(string memory uriId) internal pure returns (bool) { return bytes(uriId).length == 0; } function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal override isTier(id) { super._mint(account, id, amount, data); } function _burn( address account, uint256 id, uint256 amount ) internal override isTier(id) { super._burn(account, id, amount); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { if (to != address(0) && from != address(0)) { require( owner() == _msgSender() || from == _msgSender() || isApprovedForAll(from, _msgSender()), "Unauthorized" ); for (uint256 i; i < ids.length; i++) { require( tokenTiers[ids[i]].transferable, "Transfer disabled for this tier" ); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; library Strings { function append(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
updates transferability for a given token id (tier) tokenId tokenId for which transferability should be updated transferable determines whether tokens from tier should be transferable or not/
function updateTransferableStatus(uint256 tokenId, bool transferable) public onlyOwner isTier(tokenId) { tokenTiers[tokenId].transferable = transferable; emit TierChange(tokenId, tokenTiers[tokenId].uriId, transferable); }
10,039,462
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TheAO { address public theAO; address public nameTAOPositionAddress; // Check whether an address is whitelisted and granted access to transact // on behalf of others mapping (address => bool) public whitelist; constructor() public { theAO = msg.sender; } /** * @dev Checks if msg.sender is in whitelist. */ modifier inWhitelist() { require (whitelist[msg.sender] == true); _; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public { require (msg.sender == theAO); require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public { require (msg.sender == theAO); require (_account != address(0)); whitelist[_account] = _whitelist; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /** * @title TAOCurrency */ contract TAOCurrency is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals; // To differentiate denomination of TAO Currency uint256 public powerOfTen; uint256 public totalSupply; // This creates an array with all balances // address is the address of nameId, not the eth public address mapping (address => uint256) public balanceOf; // This generates a public event on the blockchain that will notify clients // address is the address of TAO/Name Id, not eth public address event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt // address is the address of TAO/Name Id, not eth public address event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) { _transfer(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) { _mintToken(target, mintedAmount); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title TAO */ contract TAO { using SafeMath for uint256; address public vaultAddress; string public name; // the name for this TAO address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address // TAO's data string public datHash; string public database; string public keyValue; bytes32 public contentId; /** * 0 = TAO * 1 = Name */ uint8 public typeId; /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress ) public { name = _name; originId = _originId; datHash = _datHash; database = _database; keyValue = _keyValue; contentId = _contentId; // Creating TAO typeId = 0; vaultAddress = _vaultAddress; } /** * @dev Checks if calling address is Vault contract */ modifier onlyVault { require (msg.sender == vaultAddress); _; } /** * @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) { _recipient.transfer(_amount); return true; } /** * @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); _erc20.transfer(_recipient, _amount); return true; } } /** * @title Position */ contract Position is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 4; uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4); uint256 public totalSupply; // Mapping from Name ID to bool value whether or not it has received Position Token mapping (address => bool) public receivedToken; // Mapping from Name ID to its total available balance mapping (address => uint256) public balanceOf; // Mapping from Name's TAO ID to its staked amount mapping (address => mapping(address => uint256)) public taoStakedBalance; // Mapping from TAO ID to its total staked amount mapping (address => uint256) public totalTAOStakedBalance; // This generates a public event on the blockchain that will notify clients event Mint(address indexed nameId, uint256 value); event Stake(address indexed nameId, address indexed taoId, uint256 value); event Unstake(address indexed nameId, address indexed taoId, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId` * @param _nameId Address to receive the tokens * @return true on success */ function mintToken(address _nameId) public inWhitelist returns (bool) { // Make sure _nameId has not received Position Token require (receivedToken[_nameId] == false); receivedToken[_nameId] = true; balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME); totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME); emit Mint(_nameId, MAX_SUPPLY_PER_NAME); return true; } /** * @dev Get staked balance of `_nameId` * @param _nameId The Name ID to be queried * @return total staked balance */ function stakedBalance(address _nameId) public view returns (uint256) { return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]); } /** * @dev Stake `_value` tokens on `_taoId` from `_nameId` * @param _nameId The Name ID that wants to stake * @param _taoId The TAO ID to stake * @param _value The amount to stake * @return true on success */ function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value); emit Stake(_nameId, _taoId, _value); return true; } /** * @dev Unstake `_value` tokens from `_nameId`'s `_taoId` * @param _nameId The Name ID that wants to unstake * @param _taoId The TAO ID to unstake * @param _value The amount to unstake * @return true on success */ function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value); balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance emit Unstake(_nameId, _taoId, _value); return true; } } /** * @title NameTAOLookup * */ contract NameTAOLookup is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; struct NameTAOInfo { string name; address nameTAOAddress; string parentName; uint256 typeId; // 0 = TAO. 1 = Name } uint256 public internalId; uint256 public totalNames; uint256 public totalTAOs; mapping (uint256 => NameTAOInfo) internal nameTAOInfos; mapping (bytes32 => uint256) internal internalIdLookup; /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a name exist in the list * @param _name The name to be checked * @return true if yes, false otherwise */ function isExist(string _name) public view returns (bool) { bytes32 _nameKey = keccak256(abi.encodePacked(_name)); return (internalIdLookup[_nameKey] > 0); } /** * @dev Add a new NameTAOInfo * @param _name The name of the Name/TAO * @param _nameTAOAddress The address of the Name/TAO * @param _parentName The parent name of the Name/TAO * @param _typeId If TAO = 0. Name = 1 * @return true on success */ function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) { require (bytes(_name).length > 0); require (_nameTAOAddress != address(0)); require (bytes(_parentName).length > 0); require (_typeId == 0 || _typeId == 1); require (!isExist(_name)); internalId++; bytes32 _nameKey = keccak256(abi.encodePacked(_name)); internalIdLookup[_nameKey] = internalId; NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId]; _nameTAOInfo.name = _name; _nameTAOInfo.nameTAOAddress = _nameTAOAddress; _nameTAOInfo.parentName = _parentName; _nameTAOInfo.typeId = _typeId; if (_typeId == 0) { totalTAOs++; } else { totalNames++; } return true; } /** * @dev Get the NameTAOInfo given a name * @param _name The name to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByName(string _name) public view returns (string, address, string, uint256) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Get the NameTAOInfo given an ID * @param _internalId The internal ID to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) { require (nameTAOInfos[_internalId].nameTAOAddress != address(0)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Return the nameTAOAddress given a _name * @param _name The name to be queried * @return the nameTAOAddress of the name */ function getAddressByName(string _name) public view returns (address) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return _nameTAOInfo.nameTAOAddress; } } /** * @title NamePublicKey */ contract NamePublicKey { using SafeMath for uint256; address public nameFactoryAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; struct PublicKey { bool created; address defaultKey; address[] keys; } // Mapping from nameId to its PublicKey mapping (address => PublicKey) internal publicKeys; // Event to be broadcasted to public when a publicKey is added to a Name event AddKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is removed from a Name event RemoveKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is set as default for a Name event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name ID exist in the list of Public Keys * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return publicKeys[_id].created; } /** * @dev Store the PublicKey info for a Name * @param _id The ID of the Name * @param _defaultKey The default public key for this Name * @return true on success */ function add(address _id, address _defaultKey) public isName(_id) onlyFactory returns (bool) { require (!isExist(_id)); require (_defaultKey != address(0)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.created = true; _publicKey.defaultKey = _defaultKey; _publicKey.keys.push(_defaultKey); return true; } /** * @dev Get total publicKeys count for a Name * @param _id The ID of the Name * @return total publicKeys count */ function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) { require (isExist(_id)); return publicKeys[_id].keys.length; } /** * @dev Check whether or not a publicKey exist in the list for a Name * @param _id The ID of the Name * @param _key The publicKey to check * @return true if yes. false otherwise */ function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) { require (isExist(_id)); require (_key != address(0)); PublicKey memory _publicKey = publicKeys[_id]; for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { return true; } } return false; } /** * @dev Add publicKey to list for a Name * @param _id The ID of the Name * @param _key The publicKey to be added */ function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (!isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.keys.push(_key); uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit AddKey(_id, _key, _nonce); } /** * @dev Get default public key of a Name * @param _id The ID of the Name * @return the default public key */ function getDefaultKey(address _id) public isName(_id) view returns (address) { require (isExist(_id)); return publicKeys[_id].defaultKey; } /** * @dev Get list of publicKeys of a Name * @param _id The ID of the Name * @param _from The starting index * @param _to The ending index * @return list of publicKeys */ function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) { require (isExist(_id)); require (_from >= 0 && _to >= _from); PublicKey memory _publicKey = publicKeys[_id]; require (_publicKey.keys.length > 0); address[] memory _keys = new address[](_to.sub(_from).add(1)); if (_to > _publicKey.keys.length.sub(1)) { _to = _publicKey.keys.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _keys[i.sub(_from)] = _publicKey.keys[i]; } return _keys; } /** * @dev Remove publicKey from the list * @param _id The ID of the Name * @param _key The publicKey to be removed */ function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; // Can't remove default key require (_key != _publicKey.defaultKey); require (_publicKey.keys.length > 1); for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { delete _publicKey.keys[i]; _publicKey.keys.length--; uint256 _nonce = _nameFactory.incrementNonce(_id); break; } } require (_nonce > 0); emit RemoveKey(_id, _key, _nonce); } /** * @dev Set a publicKey as the default for a Name * @param _id The ID of the Name * @param _defaultKey The defaultKey to be set * @param _signatureV The V part of the signature for this update * @param _signatureR The R part of the signature for this update * @param _signatureS The S part of the signature for this update */ function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _defaultKey)); bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey)); require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.defaultKey = _defaultKey; uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit SetDefaultKey(_id, _defaultKey, _nonce); } } /** * @title NameFactory * * The purpose of this contract is to allow node to create Name */ contract NameFactory is TheAO { using SafeMath for uint256; address public positionAddress; address public nameTAOVaultAddress; address public nameTAOLookupAddress; address public namePublicKeyAddress; Position internal _position; NameTAOLookup internal _nameTAOLookup; NameTAOPosition internal _nameTAOPosition; NamePublicKey internal _namePublicKey; address[] internal names; // Mapping from eth address to Name ID mapping (address => address) public ethAddressToNameId; // Mapping from Name ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when a Name is created event CreateName(address indexed ethAddress, address nameId, uint256 index, string name); /** * @dev Constructor function */ constructor(address _positionAddress, address _nameTAOVaultAddress) public { positionAddress = _positionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _position = Position(positionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update Name's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameTAOLookup Address * @param _nameTAOLookupAddress The address of NameTAOLookup */ function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO { require (_nameTAOLookupAddress != address(0)); nameTAOLookupAddress = _nameTAOLookupAddress; _nameTAOLookup = NameTAOLookup(nameTAOLookupAddress); } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = NamePublicKey(namePublicKeyAddress); } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a Name * @param _nameId The ID of the Name * @return current nonce */ function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) { // Check if _nameId exist require (nonces[_nameId] > 0); nonces[_nameId]++; return nonces[_nameId]; } /** * @dev Create a Name * @param _name The name of the Name * @param _datHash The datHash to this Name's profile * @param _database The database for this Name * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this Name */ function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); // Only one Name per ETH address require (ethAddressToNameId[msg.sender] == address(0)); // The address is the Name ID (which is also a TAO ID) address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[nameId]++; ethAddressToNameId[msg.sender] = nameId; // Store the name lookup information require (_nameTAOLookup.add(_name, nameId, 'human', 1)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(nameId, nameId, nameId, nameId)); // Store the public key information require (_namePublicKey.add(nameId, msg.sender)); names.push(nameId); // Need to mint Position token for this Name require (_position.mintToken(nameId)); emit CreateName(msg.sender, nameId, names.length.sub(1), _name); } /** * @dev Get Name information * @param _nameId The ID of the Name to be queried * @return The name of the Name * @return The originId of the Name (in this case, it's the creator node's ETH address) * @return The datHash of the Name * @return The database of the Name * @return The keyValue of the Name * @return The contentId of the Name * @return The typeId of the Name */ function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) { Name _name = Name(_nameId); return ( _name.name(), _name.originId(), _name.datHash(), _name.database(), _name.keyValue(), _name.contentId(), _name.typeId() ); } /** * @dev Get total Names count * @return total Names count */ function getTotalNamesCount() public view returns (uint256) { return names.length; } /** * @dev Get list of Name IDs * @param _from The starting index * @param _to The ending index * @return list of Name IDs */ function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from); require (names.length > 0); address[] memory _names = new address[](_to.sub(_from).add(1)); if (_to > names.length.sub(1)) { _to = names.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _names[i.sub(_from)] = names[i]; } return _names; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be Name's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The name of the Name * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise */ function validateNameSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public view returns (bool) { require (_nameTAOLookup.isExist(_name)); address _nameId = _nameTAOLookup.getAddressByName(_name); address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_validateAddress != address(0)) { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _validateAddress && _namePublicKey.isKeyExist(_nameId, _validateAddress) ); } else { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _namePublicKey.getDefaultKey(_nameId) ); } } } /** * @title AOStringSetting * * This contract stores all AO string setting variables */ contract AOStringSetting is TheAO { // Mapping from settingId to it's actual string value mapping (uint256 => string) public settingValue; // Mapping from settingId to it's potential string value that is at pending state mapping (uint256 => string) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The string value to be set */ function setPendingValue(uint256 _settingId, string _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { string memory _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBytesSetting * * This contract stores all AO bytes32 setting variables */ contract AOBytesSetting is TheAO { // Mapping from settingId to it's actual bytes32 value mapping (uint256 => bytes32) public settingValue; // Mapping from settingId to it's potential bytes32 value that is at pending state mapping (uint256 => bytes32) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bytes32 value to be set */ function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bytes32 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOAddressSetting * * This contract stores all AO address setting variables */ contract AOAddressSetting is TheAO { // Mapping from settingId to it's actual address value mapping (uint256 => address) public settingValue; // Mapping from settingId to it's potential address value that is at pending state mapping (uint256 => address) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The address value to be set */ function setPendingValue(uint256 _settingId, address _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { address _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBoolSetting * * This contract stores all AO bool setting variables */ contract AOBoolSetting is TheAO { // Mapping from settingId to it's actual bool value mapping (uint256 => bool) public settingValue; // Mapping from settingId to it's potential bool value that is at pending state mapping (uint256 => bool) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bool value to be set */ function setPendingValue(uint256 _settingId, bool _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bool _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOUintSetting * * This contract stores all AO uint256 setting variables */ contract AOUintSetting is TheAO { // Mapping from settingId to it's actual uint256 value mapping (uint256 => uint256) public settingValue; // Mapping from settingId to it's potential uint256 value that is at pending state mapping (uint256 => uint256) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The uint256 value to be set */ function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { uint256 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOSettingAttribute * * This contract stores all AO setting data/state */ contract AOSettingAttribute is TheAO { NameTAOPosition internal _nameTAOPosition; struct SettingData { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created the setting address creatorTAOId; // The taoId that created the setting address associatedTAOId; // The taoId that the setting affects string settingName; // The human-readable name of the setting /** * 1 => uint256 * 2 => bool * 3 => address * 4 => bytes32 * 5 => string (catch all) */ uint8 settingType; bool pendingCreate; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting string settingDataJSON; // Catch-all } struct SettingState { uint256 settingId; // Identifier of this setting bool pendingUpdate; // State when setting is in process of being updated address updateAdvocateNameId; // The nameId of the Advocate that performed the update /** * A child of the associatedTAOId with the update Logos. * This tells the setting contract that there is a proposal TAO that is a Child TAO * of the associated TAO, which will be responsible for deciding if the update to the * setting is accepted or rejected. */ address proposalTAOId; /** * Signature of the proposalTAOId and update value by the associatedTAOId * Advocate's Name's address. */ string updateSignature; /** * The proposalTAOId moves here when setting value changes successfully */ address lastUpdateTAOId; string settingStateJSON; // Catch-all } struct SettingDeprecation { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created this deprecation address creatorTAOId; // The taoId that created this deprecation address associatedTAOId; // The taoId that the setting affects bool pendingDeprecated; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting bool migrated; // State when this setting is fully migrated // holds the pending new settingId value when a deprecation is set uint256 pendingNewSettingId; // holds the new settingId that has been approved by associatedTAOId uint256 newSettingId; // holds the pending new contract address for this setting address pendingNewSettingContractAddress; // holds the new contract address for this setting address newSettingContractAddress; } struct AssociatedTAOSetting { bytes32 associatedTAOSettingId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSetting { bytes32 creatorTAOSettingId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } struct AssociatedTAOSettingDeprecation { bytes32 associatedTAOSettingDeprecationId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSettingDeprecation { bytes32 creatorTAOSettingDeprecationId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } // Mapping from settingId to it's data mapping (uint256 => SettingData) internal settingDatas; // Mapping from settingId to it's state mapping (uint256 => SettingState) internal settingStates; // Mapping from settingId to it's deprecation info mapping (uint256 => SettingDeprecation) internal settingDeprecations; // Mapping from associatedTAOSettingId to AssociatedTAOSetting mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings; // Mapping from creatorTAOSettingId to CreatorTAOSetting mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings; // Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations; // Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations; /** * @dev Constructor function */ constructor(address _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Add setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return The ID of the "Associated" setting * @return The ID of the "Creator" setting */ function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) { // Store setting data/state require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData)); // Store the associatedTAOSetting info bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; _associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId; _associatedTAOSetting.associatedTAOId = _associatedTAOId; _associatedTAOSetting.settingId = _settingId; // Store the creatorTAOSetting info bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; _creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId; _creatorTAOSetting.creatorTAOId = _creatorTAOId; _creatorTAOSetting.settingId = _settingId; return (_associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Get Setting Data of a setting ID * @param _settingId The ID of the setting */ function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) { SettingData memory _settingData = settingDatas[_settingId]; return ( _settingData.settingId, _settingData.creatorNameId, _settingData.creatorTAOId, _settingData.associatedTAOId, _settingData.settingName, _settingData.settingType, _settingData.pendingCreate, _settingData.locked, _settingData.rejected, _settingData.settingDataJSON ); } /** * @dev Get Associated TAO Setting info * @param _associatedTAOSettingId The ID of the associated tao setting */ function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) { AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; return ( _associatedTAOSetting.associatedTAOSettingId, _associatedTAOSetting.associatedTAOId, _associatedTAOSetting.settingId ); } /** * @dev Get Creator TAO Setting info * @param _creatorTAOSettingId The ID of the creator tao setting */ function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) { CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; return ( _creatorTAOSetting.creatorTAOSettingId, _creatorTAOSetting.creatorTAOId, _creatorTAOSetting.settingId ); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingData.locked = false; } else { // Reject the setting _settingData.pendingCreate = false; _settingData.rejected = true; } return true; } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == false && _settingData.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId) ); // Update the setting data _settingData.pendingCreate = false; _settingData.locked = true; return true; } /** * @dev Store setting update data * @param _settingId The ID of the setting to be updated * @param _settingType The type of this setting * @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) { // Make sure setting is created SettingData memory _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.settingType == _settingType && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) && bytes(_updateSignature).length > 0 ); // Make sure setting is not in the middle of updating SettingState storage _settingState = settingStates[_settingId]; require (_settingState.pendingUpdate == false); // Make sure setting is not yet deprecated SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; if (_settingDeprecation.settingId == _settingId) { require (_settingDeprecation.migrated == false); } // Store the SettingState data _settingState.pendingUpdate = true; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; _settingState.proposalTAOId = _proposalTAOId; _settingState.updateSignature = _updateSignature; _settingState.settingStateJSON = _extraData; return true; } /** * @dev Get setting state * @param _settingId The ID of the setting */ function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) { SettingState memory _settingState = settingStates[_settingId]; return ( _settingState.settingId, _settingState.pendingUpdate, _settingState.updateAdvocateNameId, _settingState.proposalTAOId, _settingState.updateSignature, _settingState.lastUpdateTAOId, _settingState.settingStateJSON ); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _proposalTAOAdvocate The advocate of the proposal TAO * @param _approved Whether to approve or reject * @return true on success */ function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _proposalTAOAdvocate != address(0) && _proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId) ); if (_approved) { // Unlock the setting so that advocate of associatedTAOId can finalize the update _settingData.locked = false; } else { // Set pendingUpdate to false _settingState.pendingUpdate = false; _settingState.proposalTAOId = address(0); } return true; } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _associatedTAOAdvocate The advocate of the associated TAO * @return true on success */ function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == false && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0)); // Update the setting data _settingData.locked = true; // Update the setting state _settingState.pendingUpdate = false; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; address _proposalTAOId = _settingState.proposalTAOId; _settingState.proposalTAOId = address(0); _settingState.lastUpdateTAOId = _proposalTAOId; return true; } /** * @dev Add setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return The ID of the "Associated" setting deprecation * @return The ID of the "Creator" setting deprecation */ function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) { require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress)); // Store the associatedTAOSettingDeprecation info bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId; _associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId; _associatedTAOSettingDeprecation.settingId = _settingId; // Store the creatorTAOSettingDeprecation info bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId; _creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId; _creatorTAOSettingDeprecation.settingId = _settingId; return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Get Setting Deprecation info of a setting ID * @param _settingId The ID of the setting */ function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) { SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; return ( _settingDeprecation.settingId, _settingDeprecation.creatorNameId, _settingDeprecation.creatorTAOId, _settingDeprecation.associatedTAOId, _settingDeprecation.pendingDeprecated, _settingDeprecation.locked, _settingDeprecation.rejected, _settingDeprecation.migrated, _settingDeprecation.pendingNewSettingId, _settingDeprecation.newSettingId, _settingDeprecation.pendingNewSettingContractAddress, _settingDeprecation.newSettingContractAddress ); } /** * @dev Get Associated TAO Setting Deprecation info * @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation */ function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; return ( _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId, _associatedTAOSettingDeprecation.associatedTAOId, _associatedTAOSettingDeprecation.settingId ); } /** * @dev Get Creator TAO Setting Deprecation info * @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation */ function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; return ( _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId, _creatorTAOSettingDeprecation.creatorTAOId, _creatorTAOSettingDeprecation.settingId ); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == true && _settingDeprecation.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingDeprecation.locked = false; } else { // Reject the setting _settingDeprecation.pendingDeprecated = false; _settingDeprecation.rejected = true; } return true; } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == false && _settingDeprecation.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId) ); // Update the setting data _settingDeprecation.pendingDeprecated = false; _settingDeprecation.locked = true; _settingDeprecation.migrated = true; uint256 _newSettingId = _settingDeprecation.pendingNewSettingId; _settingDeprecation.pendingNewSettingId = 0; _settingDeprecation.newSettingId = _newSettingId; address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress; _settingDeprecation.pendingNewSettingContractAddress = address(0); _settingDeprecation.newSettingContractAddress = _newSettingContractAddress; return true; } /** * @dev Check if a setting exist and not rejected * @param _settingId The ID of the setting * @return true if exist. false otherwise */ function settingExist(uint256 _settingId) public view returns (bool) { SettingData memory _settingData = settingDatas[_settingId]; return (_settingData.settingId == _settingId && _settingData.rejected == false); } /** * @dev Get the latest ID of a deprecated setting, if exist * @param _settingId The ID of the setting * @return The latest setting ID */ function getLatestSettingId(uint256 _settingId) public view returns (uint256) { (,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId); while (_migrated && _newSettingId > 0) { _settingId = _newSettingId; (,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId); } return _settingId; } /***** Internal Method *****/ /** * @dev Store setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) { // Store setting data SettingData storage _settingData = settingDatas[_settingId]; _settingData.settingId = _settingId; _settingData.creatorNameId = _creatorNameId; _settingData.creatorTAOId = _creatorTAOId; _settingData.associatedTAOId = _associatedTAOId; _settingData.settingName = _settingName; _settingData.settingType = _settingType; _settingData.pendingCreate = true; _settingData.locked = true; _settingData.settingDataJSON = _extraData; // Store setting state SettingState storage _settingState = settingStates[_settingId]; _settingState.settingId = _settingId; return true; } /** * @dev Store setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return true on success */ function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) { // Make sure this setting exists require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false); // Make sure deprecation is not yet exist for this setting Id require (settingDeprecations[_settingId].creatorNameId == address(0)); // Make sure newSettingId exists require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false); // Make sure the settingType matches require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType); // Store setting deprecation info SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; _settingDeprecation.settingId = _settingId; _settingDeprecation.creatorNameId = _creatorNameId; _settingDeprecation.creatorTAOId = _creatorTAOId; _settingDeprecation.associatedTAOId = _associatedTAOId; _settingDeprecation.pendingDeprecated = true; _settingDeprecation.locked = true; _settingDeprecation.pendingNewSettingId = _newSettingId; _settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress; return true; } } /** * @title AOTokenInterface */ contract AOTokenInterface is TheAO, TokenERC20 { using SafeMath for uint256; // To differentiate denomination of AO uint256 public powerOfTen; /***** NETWORK TOKEN VARIABLES *****/ uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; mapping (address => uint256) public stakedBalance; mapping (address => uint256) public escrowedBalance; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); event Stake(address indexed from, uint256 value); event Unstake(address indexed from, uint256 value); event Escrow(address indexed from, address indexed to, uint256 value); event Unescrow(address indexed from, uint256 value); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TokenERC20(initialSupply, tokenName, tokenSymbol) public { powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Prevent/Allow target from sending & receiving tokens * @param target Address to be frozen * @param freeze Either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyTheAO { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * @param newSellPrice Price users can sell to the contract * @param newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) { _mintToken(target, mintedAmount); return true; } /** * @dev Stake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */ function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; } /** * @dev Unstake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @return true on success */ function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unstake(_from, _value); return true; } /** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens to put in escrow * @return true on success */ function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` escrow balance * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive in escrow */ function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) { escrowedBalance[target] = escrowedBalance[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Escrow(this, target, mintedAmount); return true; } /** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network tokens to be released * @return true on success */ function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Whitelisted address transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * @dev Buy tokens from contract by sending ether */ function buy() public payable { require (buyPrice > 0); uint256 amount = msg.value.div(buyPrice); _transfer(this, msg.sender, amount); } /** * @dev Sell `amount` tokens to contract * @param amount The amount of tokens to be sold */ function sell(uint256 amount) public { require (sellPrice > 0); address myAddress = this; require (myAddress.balance >= amount.mul(sellPrice)); _transfer(msg.sender, this, amount); msg.sender.transfer(amount.mul(sellPrice)); } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title AOToken */ contract AOToken is AOTokenInterface { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; // AO Dev Team addresses to receive Primordial/Network Tokens address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52; address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28; AOSetting internal _aoSetting; /***** PRIMORDIAL TOKEN VARIABLES *****/ uint256 public primordialTotalSupply; uint256 public primordialTotalBought; uint256 public primordialSellPrice; uint256 public primordialBuyPrice; // Total available primordial token for sale 1,125,899,906,842,620 AO+ uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620; mapping (address => uint256) public primordialBalanceOf; mapping (address => mapping (address => uint256)) public primordialAllowance; // Mapping from owner's lot weighted multiplier to the amount of staked tokens mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance; event PrimordialTransfer(address indexed from, address indexed to, uint256 value); event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value); event PrimordialBurn(address indexed from, uint256 value); event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier); event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier); uint256 public totalLots; uint256 public totalBurnLots; uint256 public totalConvertLots; bool public networkExchangeEnded; /** * Stores Lot creation data (during network exchange) */ struct Lot { bytes32 lotId; uint256 multiplier; // This value is in 10^6, so 1000000 = 1 address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account burns primordial token */ struct BurnLot { bytes32 burnLotId; address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account converts network token to primordial token */ struct ConvertLot { bytes32 convertLotId; address lotOwner; uint256 tokenAmount; } // Mapping from Lot ID to Lot object mapping (bytes32 => Lot) internal lots; // Mapping from Burn Lot ID to BurnLot object mapping (bytes32 => BurnLot) internal burnLots; // Mapping from Convert Lot ID to ConvertLot object mapping (bytes32 => ConvertLot) internal convertLots; // Mapping from owner to list of owned lot IDs mapping (address => bytes32[]) internal ownedLots; // Mapping from owner to list of owned burn lot IDs mapping (address => bytes32[]) internal ownedBurnLots; // Mapping from owner to list of owned convert lot IDs mapping (address => bytes32[]) internal ownedConvertLots; // Mapping from owner to his/her current weighted multiplier mapping (address => uint256) internal ownerWeightedMultiplier; // Mapping from owner to his/her max multiplier (multiplier of account's first Lot) mapping (address => uint256) internal ownerMaxMultiplier; // Event to be broadcasted to public when a lot is created // multiplier value is in 10^6 to account for 6 decimal points event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount); // Event to be broadcasted to public when burn lot is created (when account burns primordial tokens) event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn); // Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens) event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress) AOTokenInterface(initialSupply, tokenName, tokenSymbol) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; _aoSetting = AOSetting(_aoSettingAddress); powerOfTen = 0; decimals = 0; setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token } /** * @dev Checks if buyer can buy primordial token */ modifier canBuyPrimordial(uint256 _sentAmount) { require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0); _; } /***** The AO ONLY METHODS *****/ /** * @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange * @param _aoDevTeam1 The first AO dev team address * @param _aoDevTeam2 The second AO dev team address */ function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO { aoDevTeam1 = _aoDevTeam1; aoDevTeam2 = _aoDevTeam2; } /***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/ /** * @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth * @param newPrimordialSellPrice Price users can sell to the contract * @param newPrimordialBuyPrice Price users can buy from the contract */ function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO { primordialSellPrice = newPrimordialSellPrice; primordialBuyPrice = newPrimordialBuyPrice; } /***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from` * @param _from The address of the target * @param _value The amount of Primordial tokens to stake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted balance is enough require (primordialBalanceOf[_from] >= _value); // Make sure the weighted multiplier is the same as account's current weighted multiplier require (_weightedMultiplier == ownerWeightedMultiplier[_from]); // Subtract from the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Add to the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value); emit PrimordialStake(_from, _value, _weightedMultiplier); return true; } /** * @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted staked balance is enough require (primordialStakedBalance[_from][_weightedMultiplier] >= _value); // Subtract from the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value); // Add to the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value); emit PrimordialUnstake(_from, _value, _weightedMultiplier); return true; } /** * @dev Send `_value` primordial tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /***** PUBLIC METHODS *****/ /***** Primordial TOKEN PUBLIC METHODS *****/ /** * @dev Buy Primordial tokens from contract by sending ether */ function buyPrimordialToken() public payable canBuyPrimordial(msg.value) { (uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value); require (tokenAmount > 0); // Ends network exchange if necessary if (shouldEndNetworkExchange) { networkExchangeEnded = true; } // Send the primordial token to buyer and reward AO devs _sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender); // Send remainder budget back to buyer if exist if (remainderBudget > 0) { msg.sender.transfer(remainderBudget); } } /** * @dev Send `_value` Primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(msg.sender, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Send `_value` Primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (_value <= primordialAllowance[_from][msg.sender]); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount they can spend * @return true on success */ function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) { primordialAllowance[msg.sender][_spender] = _value; emit PrimordialApproval(msg.sender, _spender, _value); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approvePrimordialToken(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Remove `_value` Primordial tokens from the system irreversibly * and re-weight the account's multiplier after burn * @param _value The amount to burn * @return true on success */ function burnPrimordialToken(uint256 _value) public returns (bool success) { require (primordialBalanceOf[msg.sender] >= _value); require (calculateMaximumBurnAmount(msg.sender) >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value); primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(msg.sender, _value); emit PrimordialBurn(msg.sender, _value); return true; } /** * @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from` * and re-weight `_from`'s multiplier after burn * @param _from The address of sender * @param _value The amount to burn * @return true on success */ function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) { require (primordialBalanceOf[_from] >= _value); require (primordialAllowance[_from][msg.sender] >= _value); require (calculateMaximumBurnAmount(_from) >= _value); // Update `_from`'s multiplier ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(_from, _value); emit PrimordialBurn(_from, _value); return true; } /** * @dev Return all lot IDs owned by an address * @param _lotOwner The address of the lot owner * @return array of lot IDs */ function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedLots[_lotOwner]; } /** * @dev Return the total lots owned by an address * @param _lotOwner The address of the lot owner * @return total lots owner by the address */ function totalLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedLots[_lotOwner].length; } /** * @dev Return the lot information at a given index of the lots list of the requested owner * @param _lotOwner The address owning the lots list to be accessed * @param _index uint256 representing the index to be accessed of the requested lots list * @return id of the lot * @return The address of the lot owner * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) { require (_index < ownedLots[_lotOwner].length); Lot memory _lot = lots[ownedLots[_lotOwner][_index]]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return the lot information at a given ID * @param _lotId The lot ID in question * @return id of the lot * @return The lot owner address * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) { Lot memory _lot = lots[_lotId]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return all Burn Lot IDs owned by an address * @param _lotOwner The address of the burn lot owner * @return array of Burn Lot IDs */ function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedBurnLots[_lotOwner]; } /** * @dev Return the total burn lots owned by an address * @param _lotOwner The address of the burn lot owner * @return total burn lots owner by the address */ function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedBurnLots[_lotOwner].length; } /** * @dev Return the burn lot information at a given ID * @param _burnLotId The burn lot ID in question * @return id of the lot * @return The address of the burn lot owner * @return Primordial token amount in the burn lot */ function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) { BurnLot memory _burnLot = burnLots[_burnLotId]; return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount); } /** * @dev Return all Convert Lot IDs owned by an address * @param _lotOwner The address of the convert lot owner * @return array of Convert Lot IDs */ function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedConvertLots[_lotOwner]; } /** * @dev Return the total convert lots owned by an address * @param _lotOwner The address of the convert lot owner * @return total convert lots owner by the address */ function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedConvertLots[_lotOwner].length; } /** * @dev Return the convert lot information at a given ID * @param _convertLotId The convert lot ID in question * @return id of the lot * @return The address of the convert lot owner * @return Primordial token amount in the convert lot */ function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) { ConvertLot memory _convertLot = convertLots[_convertLotId]; return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount); } /** * @dev Return the average weighted multiplier of all lots owned by an address * @param _lotOwner The address of the lot owner * @return the weighted multiplier of the address (in 10 ** 6) */ function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) { return ownerWeightedMultiplier[_lotOwner]; } /** * @dev Return the max multiplier of an address * @param _target The address to query * @return the max multiplier of the address (in 10 ** 6) */ function maxMultiplierByAddress(address _target) public view returns (uint256) { return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0; } /** * @dev Calculate the primordial token multiplier, bonus network token percentage, and the * bonus network token amount on a given lot when someone purchases primordial token * during network exchange * @param _purchaseAmount The amount of primordial token intended to be purchased * @return The multiplier in (10 ** 6) * @return The bonus percentage * @return The amount of network token as bonus */ function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); return ( AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier), AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier), AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier) ); } /** * @dev Calculate the maximum amount of Primordial an account can burn * @param _account The address of the account * @return The maximum primordial token amount to burn */ function calculateMaximumBurnAmount(address _account) public view returns (uint256) { return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]); } /** * @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens * @param _account The address of the account * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) { require (calculateMaximumBurnAmount(_account) >= _amountToBurn); return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn); } /** * @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token * @param _account The address of the account * @param _amountToConvert The amount of network token to convert * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) { return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert); } /** * @dev Convert `_value` of network tokens to primordial tokens * and re-weight the account's multiplier after conversion * @param _value The amount to convert * @return true on success */ function convertToPrimordial(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value); // Burn network token burn(_value); // mint primordial token _mintPrimordialToken(msg.sender, _value); // Store convert lot info totalConvertLots++; // Generate convert lot Id bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots)); // Make sure no one owns this lot yet require (convertLots[convertLotId].lotOwner == address(0)); ConvertLot storage convertLot = convertLots[convertLotId]; convertLot.convertLotId = convertLotId; convertLot.lotOwner = msg.sender; convertLot.tokenAmount = _value; ownedConvertLots[msg.sender].push(convertLotId); emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]); return true; } /***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/ /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount of network tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transfer(_to, _value)); require (transferPrimordialToken(_to, _primordialValue)); return true; } /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transferFrom(_from, _to, _value)); require (transferPrimordialTokenFrom(_from, _to, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of network tokens they can spend * @return true on success */ function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.approve(_spender, _value)); require (approvePrimordialToken(_spender, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of Primordial Tokens they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) { require (super.approveAndCall(_spender, _value, _extraData)); require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burn(_value)); require (burnPrimordialToken(_primordialValue)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from` * @param _from The address of sender * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burnFrom(_from, _value)); require (burnPrimordialTokenFrom(_from, _primordialValue)); return true; } /***** INTERNAL METHODS *****/ /***** PRIMORDIAL TOKEN INTERNAL METHODS *****/ /** * @dev Calculate the amount of token the buyer will receive and remaining budget if exist * when he/she buys primordial token * @param _budget The amount of ETH sent by buyer * @return uint256 of the tokenAmount the buyer will receiver * @return uint256 of the remaining budget, if exist * @return bool whether or not the network exchange should end */ function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) { // Calculate the amount of tokens uint256 tokenAmount = _budget.div(primordialBuyPrice); // If we need to return ETH to the buyer, in the case // where the buyer sends more ETH than available primordial token to be purchased uint256 remainderEth = 0; // Make sure primordialTotalBought is not overflowing bool shouldEndNetworkExchange = false; if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) { tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought); shouldEndNetworkExchange = true; remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice)); } return (tokenAmount, remainderEth, shouldEndNetworkExchange); } /** * @dev Actually sending the primordial token to buyer and reward AO devs accordingly * @param tokenAmount The amount of primordial token to be sent to buyer * @param to The recipient of the token */ function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal { (uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); // Update primordialTotalBought (uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount); primordialTotalBought = primordialTotalBought.add(tokenAmount); _createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount); // Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR()); if (aoDevTeam1 != address(0)) { _createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } if (aoDevTeam2 != address(0)) { _createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } _mintToken(theAO, theAONetworkTokenBonusAmount); } /** * @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account` * during network exchange, and reward `_networkTokenBonusAmount` if exist * @param _account Address of the lot owner * @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot * @param _multiplier The multiplier for this lot in (10 ** 6) * @param _networkTokenBonusAmount The network token bonus amount */ function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal { totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _multiplier; lot.lotOwner = _account; lot.tokenAmount = _primordialTokenAmount; ownedLots[_account].push(lotId); ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } _mintPrimordialToken(_account, lot.tokenAmount); _mintToken(_account, _networkTokenBonusAmount); emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount); } /** * @dev Create `mintedAmount` Primordial tokens and send it to `target` * @param target Address to receive the Primordial tokens * @param mintedAmount The amount of Primordial tokens it will receive */ function _mintPrimordialToken(address target, uint256 mintedAmount) internal { primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount); primordialTotalSupply = primordialTotalSupply.add(mintedAmount); emit PrimordialTransfer(0, this, mintedAmount); emit PrimordialTransfer(this, target, mintedAmount); } /** * @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account` * @param _account Address of lot owner * @param _tokenAmount The amount of tokens * @param _weightedMultiplier The multiplier of the lot (in 10^6) * @return bytes32 of new created lot ID */ function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) { require (_account != address(0)); require (_tokenAmount > 0); totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _weightedMultiplier; lot.lotOwner = _account; lot.tokenAmount = _tokenAmount; ownedLots[_account].push(lotId); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } return lotId; } /** * @dev Send `_value` Primordial tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient emit PrimordialTransfer(_from, _to, _value); assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances); return true; } /** * @dev Store burn lot information * @param _account The address of the account * @param _tokenAmount The amount of primordial tokens to burn */ function _createBurnLot(address _account, uint256 _tokenAmount) internal { totalBurnLots++; // Generate burn lot Id bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots)); // Make sure no one owns this lot yet require (burnLots[burnLotId].lotOwner == address(0)); BurnLot storage burnLot = burnLots[burnLotId]; burnLot.burnLotId = burnLotId; burnLot.lotOwner = _account; burnLot.tokenAmount = _tokenAmount; ownedBurnLots[_account].push(burnLotId); emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]); } /** * @dev Get setting variables * @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token * @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token * @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus * @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus */ function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier'); (uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier'); (uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier'); (uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier'); return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier); } } /** * @title AOTreasury * * The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations */ contract AOTreasury is TheAO { using SafeMath for uint256; bool public paused; bool public killed; struct Denomination { bytes8 name; address denominationAddress; } // Mapping from denomination index to Denomination object // The list is in order from lowest denomination to highest denomination // i.e, denominations[1] is the base denomination mapping (uint256 => Denomination) internal denominations; // Mapping from denomination ID to index of denominations mapping (bytes8 => uint256) internal denominationIndex; uint256 public totalDenominations; // Event to be broadcasted to public when a token exchange happens event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /** * @dev Checks if denomination is valid */ modifier isValidDenomination(bytes8 denominationName) { require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO adds denomination and the contract address associated with it * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationAddress != address(0)); require (denominationIndex[denominationName] == 0); totalDenominations++; // Make sure the new denomination is higher than the previous if (totalDenominations > 1) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress); AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen()); } denominations[totalDenominations].name = denominationName; denominations[totalDenominations].denominationAddress = denominationAddress; denominationIndex[denominationName] = totalDenominations; return true; } /** * @dev The AO updates denomination address or activates/deactivates the denomination * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominationAddress != address(0)); uint256 _denominationNameIndex = denominationIndex[denominationName]; AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); if (_denominationNameIndex > 1) { AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress); require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen()); } if (_denominationNameIndex < totalDenominations) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress); require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen()); } denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress; return true; } /***** PUBLIC METHODS *****/ /** * @dev Get denomination info based on name * @param denominationName The name to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominations[denominationIndex[denominationName]].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress); return ( denominations[denominationIndex[denominationName]].name, denominations[denominationIndex[denominationName]].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get denomination info by index * @param index The index to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) { require (index > 0 && index <= totalDenominations); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get base denomination info * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) { require (totalDenominations > 1); return getDenominationByIndex(1); } /** * @dev convert token from `denominationName` denomination to base denomination, * in this case it's similar to web3.toWei() functionality * * Example: * 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount * 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount * 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount * * @param integerAmount uint256 of the integer amount to be converted * @param fractionAmount uint256 of the frational amount to be converted * @param denominationName bytes8 name of the token denomination * @return uint256 converted amount in base denomination from target denomination */ function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) { if (denominationName.length > 0 && denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0) && (integerAmount > 0 || fractionAmount > 0)) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint8 fractionNumDigits = _numDigits(fractionAmount); require (fractionNumDigits <= _denominationToken.decimals()); uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen()); if (_denominationToken.decimals() == 0) { fractionAmount = 0; } return baseInteger.add(fractionAmount); } else { return 0; } } /** * @dev convert token from base denomination to `denominationName` denomination, * in this case it's similar to web3.fromWei() functionality * @param integerAmount uint256 of the base amount to be converted * @param denominationName bytes8 name of the target token denomination * @return uint256 of the converted integer amount in target denomination * @return uint256 of the converted fraction amount in target denomination */ function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen()); uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen())); return (denominationInteger, denominationFraction); } /** * @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination * @param amount The amount of token to exchange * @param fromDenominationName The origin denomination * @param toDenominationName The target denomination */ function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) { require (amount > 0); Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]]; Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]]; AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress); AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress); require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount)); require (_toDenominationToken.mintToken(msg.sender, amount)); emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName); } /** * @dev Return the highest possible denomination given a base amount * @param amount The amount to be converted * @return the denomination short name * @return the denomination address * @return the integer amount at the denomination level * @return the fraction amount at the denomination level * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) { uint256 integerAmount; uint256 fractionAmount; uint256 index; for (uint256 i=totalDenominations; i>0; i--) { Denomination memory _denomination = denominations[i]; (integerAmount, fractionAmount) = fromBase(amount, _denomination.name); if (integerAmount > 0) { index = i; break; } } require (index > 0 && index <= totalDenominations); require (integerAmount > 0 || fractionAmount > 0); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, integerAmount, fractionAmount, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /***** INTERNAL METHOD *****/ /** * @dev count num of digits * @param number uint256 of the nuumber to be checked * @return uint8 num of digits */ function _numDigits(uint256 number) internal pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; } } contract Pathos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } contract Ethos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } /** * @title TAOController */ contract TAOController { NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of TAO ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } } // Store the name lookup for a Name/TAO /** * @title TAOFamily */ contract TAOFamily is TAOController { using SafeMath for uint256; address public taoFactoryAddress; TAOFactory internal _taoFactory; struct Child { address taoId; bool approved; // If false, then waiting for parent TAO approval bool connected; // If false, then parent TAO want to remove this child TAO } struct Family { address taoId; address parentId; // The parent of this TAO ID (could be a Name or TAO) uint256 childMinLogos; mapping (uint256 => Child) children; mapping (address => uint256) childInternalIdLookup; uint256 totalChildren; uint256 childInternalId; } mapping (address => Family) internal families; // Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce); // Event to be broadcasted to public when a TAO adds a child TAO event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce); // Event to be broadcasted to public when a TAO approves a child TAO event ApproveChild(address indexed taoId, address childId, uint256 nonce); // Event to be broadcasted to public when a TAO removes a child TAO event RemoveChild(address indexed taoId, address childId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == taoFactoryAddress); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a TAO ID exist in the list of families * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return families[_id].taoId != address(0); } /** * @dev Store the Family info for a TAO * @param _id The ID of the TAO * @param _parentId The parent ID of this TAO * @param _childMinLogos The min required Logos to create a TAO * @return true on success */ function add(address _id, address _parentId, uint256 _childMinLogos) public isTAO(_id) isNameOrTAO(_parentId) onlyFactory returns (bool) { require (!isExist(_id)); Family storage _family = families[_id]; _family.taoId = _id; _family.parentId = _parentId; _family.childMinLogos = _childMinLogos; return true; } /** * @dev Get Family info given a TAO ID * @param _id The ID of the TAO * @return the parent ID of this TAO (could be a Name/TAO) * @return the min required Logos to create a child TAO * @return the total child TAOs count */ function getFamilyById(address _id) public view returns (address, uint256, uint256) { require (isExist(_id)); Family memory _family = families[_id]; return ( _family.parentId, _family.childMinLogos, _family.totalChildren ); } /** * @dev Set min required Logos to create a child from this TAO * @param _childMinLogos The min Logos to set * @return the nonce for this transaction */ function updateChildMinLogos(address _id, uint256 _childMinLogos) public isTAO(_id) senderIsName() onlyAdvocate(_id) { require (isExist(_id)); Family storage _family = families[_id]; _family.childMinLogos = _childMinLogos; uint256 _nonce = _taoFactory.incrementNonce(_id); require (_nonce > 0); emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce); } /** * @dev Check if `_childId` is a child TAO of `_taoId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to check * @return true if yes. Otherwise return false. */ function isChild(address _taoId, address _childId) public view returns (bool) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family memory _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; return ( _childInternalId > 0 && _family.children[_childInternalId].approved && _family.children[_childInternalId].connected && _childFamily.parentId == _taoId ); } /** * @dev Add child TAO * @param _taoId The TAO ID to be added to * @param _childId The ID to be added to as child TAO */ function addChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) onlyFactory returns (bool) { require (!isChild(_taoId, _childId)); Family storage _family = families[_taoId]; require (_family.childInternalIdLookup[_childId] == 0); _family.childInternalId++; _family.childInternalIdLookup[_childId] = _family.childInternalId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); Child storage _child = _family.children[_family.childInternalId]; _child.taoId = _childId; // If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected // Otherwise, child TAO needs parent TAO approval address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId); address _childAdvocate = _nameTAOPosition.getAdvocate(_childId); if (_taoAdvocate == _childAdvocate) { _family.totalChildren++; _child.approved = true; _child.connected = true; Family storage _childFamily = families[_childId]; _childFamily.parentId = _taoId; } emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce); return true; } /** * @dev Advocate of `_taoId` approves child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be approved */ function approveChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family storage _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; require (_childInternalId > 0 && !_family.children[_childInternalId].approved && !_family.children[_childInternalId].connected ); _family.totalChildren++; Child storage _child = _family.children[_childInternalId]; _child.approved = true; _child.connected = true; _childFamily.parentId = _taoId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit ApproveChild(_taoId, _childId, _nonce); } /** * @dev Advocate of `_taoId` removes child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be removed */ function removeChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isChild(_taoId, _childId)); Family storage _family = families[_taoId]; _family.totalChildren--; Child storage _child = _family.children[_family.childInternalIdLookup[_childId]]; _child.connected = false; _family.childInternalIdLookup[_childId] = 0; Family storage _childFamily = families[_childId]; _childFamily.parentId = address(0); uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit RemoveChild(_taoId, _childId, _nonce); } /** * @dev Get list of child TAO IDs * @param _taoId The TAO ID to be checked * @param _from The starting index (start from 1) * @param _to The ending index, (max is childInternalId) * @return list of child TAO IDs */ function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) { require (isExist(_taoId)); Family storage _family = families[_taoId]; require (_from >= 1 && _to >= _from && _family.childInternalId >= _to); address[] memory _childIds = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0); } return _childIds; } } // Store TAO's child information /** * @title TAOFactory * * The purpose of this contract is to allow node to create TAO */ contract TAOFactory is TheAO, TAOController { using SafeMath for uint256; address[] internal taos; address public taoFamilyAddress; address public nameTAOVaultAddress; address public settingTAOId; NameTAOLookup internal _nameTAOLookup; TAOFamily internal _taoFamily; AOSetting internal _aoSetting; Logos internal _logos; // Mapping from TAO ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when Advocate creates a TAO event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSetting = AOSetting(_aoSettingAddress); _logos = Logos(_logosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update TAO's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the TAOFamily Address * @param _taoFamilyAddress The address of TAOFamily */ function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO { require (_taoFamilyAddress != address(0)); taoFamilyAddress = _taoFamilyAddress; _taoFamily = TAOFamily(taoFamilyAddress); } /** * @dev The AO set settingTAOId (The TAO ID that holds the setting values) * @param _settingTAOId The address of settingTAOId */ function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) { settingTAOId = _settingTAOId; } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a TAO * @param _taoId The ID of the TAO * @return current nonce */ function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) { // Check if _taoId exist require (nonces[_taoId] > 0); nonces[_taoId]++; return nonces[_taoId]; } /** * @dev Name creates a TAO * @param _name The name of the TAO * @param _datHash The datHash of this TAO * @param _database The database for this TAO * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this TAO * @param _parentId The parent of this TAO (has to be a Name or TAO) * @param _childMinLogos The min required Logos to create a child from this TAO */ function createTAO( string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _parentId, uint256 _childMinLogos ) public senderIsName() isNameOrTAO(_parentId) { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); address _nameId = _nameFactory.ethAddressToNameId(msg.sender); uint256 _parentCreateChildTAOMinLogos; uint256 _createChildTAOMinLogos = _getSettingVariables(); if (AOLibrary.isTAO(_parentId)) { (, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId); } if (_parentCreateChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos); } else if (_createChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos); } // Create the TAO address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[taoId]++; // Store the name lookup information require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId)); require (_taoFamily.add(taoId, _parentId, _childMinLogos)); taos.push(taoId); emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId()); if (AOLibrary.isTAO(_parentId)) { require (_taoFamily.addChild(_parentId, taoId)); } } /** * @dev Get TAO information * @param _taoId The ID of the TAO to be queried * @return The name of the TAO * @return The origin Name ID that created the TAO * @return The name of Name that created the TAO * @return The datHash of the TAO * @return The database of the TAO * @return The keyValue of the TAO * @return The contentId of the TAO * @return The typeId of the TAO */ function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) { TAO _tao = TAO(_taoId); return ( _tao.name(), _tao.originId(), Name(_tao.originId()).name(), _tao.datHash(), _tao.database(), _tao.keyValue(), _tao.contentId(), _tao.typeId() ); } /** * @dev Get total TAOs count * @return total TAOs count */ function getTotalTAOsCount() public view returns (uint256) { return taos.length; } /** * @dev Get list of TAO IDs * @param _from The starting index * @param _to The ending index * @return list of TAO IDs */ function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from && taos.length > _to); address[] memory _taos = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _taos[i.sub(_from)] = taos[i]; } return _taos; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The Name of the TAO * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise * @return The name of the Name that created the signature * @return The Position of the Name that created the signature. * 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker */ function validateTAOSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) { address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) { return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name))); } else { return (false, "", 0); } } /***** INTERNAL METHOD *****/ /** * @dev Check whether or not the address recovered from the signature is valid * @param _validateAddress The ETH address to be validated (optional) * @param _signatureAddress The address recovered from the signature * @param _taoId The ID of the TAO * @param _nonce The signed uint256 nonce * @return true if valid. false otherwise */ function _isTAOSignatureAddressValid( address _validateAddress, address _signatureAddress, address _taoId, uint256 _nonce ) internal view returns (bool) { if (_validateAddress != address(0)) { return (_nonce == nonces[_taoId].add(1) && _signatureAddress == _validateAddress && _nameTAOPosition.senderIsPosition(_validateAddress, _taoId) ); } else { return ( _nonce == nonces[_taoId].add(1) && _nameTAOPosition.senderIsPosition(_signatureAddress, _taoId) ); } } /** * @dev Internal function to get the TAO Id by name * @param _name The name of the TAO * @return the TAO ID */ function _getTAOIdByName(string _name) internal view returns (address) { return _nameTAOLookup.getAddressByName(_name); } /** * @dev Get setting variables * @return createChildTAOMinLogos The minimum required Logos to create a TAO */ function _getSettingVariables() internal view returns (uint256) { (uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos'); return createChildTAOMinLogos; } } /** * @title NameTAOPosition */ contract NameTAOPosition is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; NameFactory internal _nameFactory; TAOFactory internal _taoFactory; struct Position { address advocateId; address listenerId; address speakerId; bool created; } mapping (address => Position) internal positions; // Event to be broadcasted to public when current Advocate of TAO sets New Advocate event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); nameTAOPositionAddress = address(this); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of a Name/TAO ID */ modifier onlyAdvocate(address _id) { require (senderIsAdvocate(msg.sender, _id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name/TAO ID exist in the list * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return positions[_id].created; } /** * @dev Check whether or not eth address is advocate of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsAdvocate(address _sender, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender)); } /** * @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsPosition(address _sender, address _id) public view returns (bool) { address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == address(0)) { return false; } else { return (positions[_id].created && (positions[_id].advocateId == _nameId || positions[_id].listenerId == _nameId || positions[_id].speakerId == _nameId ) ); } } /** * @dev Check whether or not _nameId is advocate of _id * @param _nameId The name ID to be checked * @param _id The ID to be checked * @return true if yes, false otherwise */ function nameIsAdvocate(address _nameId, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameId); } /** * @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO * @param _sender The ETH address that to check * @param _id The ID of the Name/TAO * @return 1 if Advocate. 2 if Listener. 3 if Speaker */ function determinePosition(address _sender, address _id) public view returns (uint256) { require (senderIsPosition(_sender, _id)); Position memory _position = positions[_id]; address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == _position.advocateId) { return 1; } else if (_nameId == _position.listenerId) { return 2; } else { return 3; } } /** * @dev Add Position for a Name/TAO * @param _id The ID of the Name/TAO * @param _advocateId The Advocate ID of the Name/TAO * @param _listenerId The Listener ID of the Name/TAO * @param _speakerId The Speaker ID of the Name/TAO * @return true on success */ function add(address _id, address _advocateId, address _listenerId, address _speakerId) public isNameOrTAO(_id) isName(_advocateId) isNameOrTAO(_listenerId) isNameOrTAO(_speakerId) onlyFactory returns (bool) { require (!isExist(_id)); Position storage _position = positions[_id]; _position.advocateId = _advocateId; _position.listenerId = _listenerId; _position.speakerId = _speakerId; _position.created = true; return true; } /** * @dev Get Name/TAO's Position info * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO * @return the Listener ID of Name/TAO * @return the Speaker ID of Name/TAO */ function getPositionById(address _id) public view returns (address, address, address) { require (isExist(_id)); Position memory _position = positions[_id]; return ( _position.advocateId, _position.listenerId, _position.speakerId ); } /** * @dev Get Name/TAO's Advocate * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO */ function getAdvocate(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.advocateId; } /** * @dev Get Name/TAO's Listener * @param _id The ID of the Name/TAO * @return the Listener ID of Name/TAO */ function getListener(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.listenerId; } /** * @dev Get Name/TAO's Speaker * @param _id The ID of the Name/TAO * @return the Speaker ID of Name/TAO */ function getSpeaker(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.speakerId; } /** * @dev Set Advocate for a TAO * @param _taoId The ID of the TAO * @param _newAdvocateId The new advocate ID to be set */ function setAdvocate(address _taoId, address _newAdvocateId) public isTAO(_taoId) isName(_newAdvocateId) senderIsName() onlyAdvocate(_taoId) { Position storage _position = positions[_taoId]; address _currentAdvocateId = _position.advocateId; _position.advocateId = _newAdvocateId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce); } /** * @dev Set Listener for a Name/TAO * @param _id The ID of the Name/TAO * @param _newListenerId The new listener ID to be set */ function setListener(address _id, address _newListenerId) public isNameOrTAO(_id) isNameOrTAO(_newListenerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Listener can only be a Name // If _id is a TAO, then new Listener can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newListenerId)); } Position storage _position = positions[_id]; address _currentListenerId = _position.listenerId; _position.listenerId = _newListenerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce); } /** * @dev Set Speaker for a Name/TAO * @param _id The ID of the Name/TAO * @param _newSpeakerId The new speaker ID to be set */ function setSpeaker(address _id, address _newSpeakerId) public isNameOrTAO(_id) isNameOrTAO(_newSpeakerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Speaker can only be a Name // If _id is a TAO, then new Speaker can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newSpeakerId)); } Position storage _position = positions[_id]; address _currentSpeakerId = _position.speakerId; _position.speakerId = _newSpeakerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce); } } /** * @title AOSetting * * This contract stores all AO setting variables */ contract AOSetting { address public aoSettingAttributeAddress; address public aoUintSettingAddress; address public aoBoolSettingAddress; address public aoAddressSettingAddress; address public aoBytesSettingAddress; address public aoStringSettingAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; AOSettingAttribute internal _aoSettingAttribute; AOUintSetting internal _aoUintSetting; AOBoolSetting internal _aoBoolSetting; AOAddressSetting internal _aoAddressSetting; AOBytesSetting internal _aoBytesSetting; AOStringSetting internal _aoStringSetting; uint256 public totalSetting; /** * Mapping from associatedTAOId's setting name to Setting ID. * * Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup, * use nested mapping to achieve the same result. * * The setting's name needs to be converted to bytes32 since solidity does not support mapping by string. */ mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup; // Mapping from updateHashKey to it's settingId mapping (bytes32 => uint256) public updateHashLookup; // Event to be broadcasted to public when a setting is created and waiting for approval event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId); // Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); // Event to be broadcasted to public when a proposed update for a setting is created event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId); // Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved); // Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate); // Event to be broadcasted to public when a setting deprecation is created and waiting for approval event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId); // Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _aoSettingAttributeAddress, address _aoUintSettingAddress, address _aoBoolSettingAddress, address _aoAddressSettingAddress, address _aoBytesSettingAddress, address _aoStringSettingAddress) public { aoSettingAttributeAddress = _aoSettingAttributeAddress; aoUintSettingAddress = _aoUintSettingAddress; aoBoolSettingAddress = _aoBoolSettingAddress; aoAddressSettingAddress = _aoAddressSettingAddress; aoBytesSettingAddress = _aoBytesSettingAddress; aoStringSettingAddress = _aoStringSettingAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress); _aoUintSetting = AOUintSetting(_aoUintSettingAddress); _aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress); _aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress); _aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress); _aoStringSetting = AOStringSetting(_aoStringSettingAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_settingName` of `_associatedTAOId` is taken */ modifier settingNameNotTaken(string _settingName, address _associatedTAOId) { require (settingNameExist(_settingName, _associatedTAOId) == false); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** Public Methods *****/ /** * @dev Check whether or not a setting name of an associatedTAOId exist * @param _settingName The human-readable name of the setting * @param _associatedTAOId The taoId that the setting affects * @return true if yes. false otherwise */ function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) { return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0); } /** * @dev Advocate of _creatorTAOId adds a uint setting * @param _settingName The human-readable name of the setting * @param _value The uint256 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoUintSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bool setting * @param _settingName The human-readable name of the setting * @param _value The bool value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBoolSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds an address setting * @param _settingName The human-readable name of the setting * @param _value The address value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoAddressSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bytes32 setting * @param _settingName The human-readable name of the setting * @param _value The bytes32 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBytesSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a string setting * @param _settingName The human-readable name of the setting * @param _value The string value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoStringSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingCreation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved)); (,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId); if (!_approved) { // Clear the settingName from nameSettingLookup so it can be added again in the future delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingCreation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate)); (,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new uint256 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoUintSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bool value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBoolSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoAddressSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bytes32 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBytesSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new string value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoStringSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _approved Whether to approve or reject */ function approveSettingUpdate(uint256 _settingId, bool _approved) public { address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); (,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId); require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved)); emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingUpdate(uint256 _settingId) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate)); (,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate); } /** * @dev Advocate of _creatorTAOId adds a setting deprecation * @param _settingId The ID of the setting to be deprecated * @param _newSettingId The new setting ID to route * @param _newSettingContractAddress The new setting contract address to route * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects */ function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) { (bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress); emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingDeprecation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved)); (,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingDeprecation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate)); (,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Get setting Id given an associatedTAOId and settingName * @param _associatedTAOId The ID of the AssociatedTAO * @param _settingName The name of the setting * @return the ID of the setting */ function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) { return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } /** * @dev Get setting values by setting ID. * Will throw error if the setting is not exist or rejected. * @param _settingId The ID of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) { require (_aoSettingAttribute.settingExist(_settingId)); _settingId = _aoSettingAttribute.getLatestSettingId(_settingId); return ( _aoUintSetting.settingValue(_settingId), _aoBoolSetting.settingValue(_settingId), _aoAddressSetting.settingValue(_settingId), _aoBytesSetting.settingValue(_settingId), _aoStringSetting.settingValue(_settingId) ); } /** * @dev Get setting values by taoId and settingName. * Will throw error if the setting is not exist or rejected. * @param _taoId The ID of the TAO * @param _settingName The name of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) { return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName)); } /***** Internal Method *****/ /** * @dev Store setting creation data * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal { // Make sure _settingType is in supported list require (_settingType >= 1 && _settingType <= 5); // Store nameSettingLookup nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting; // Store setting data/state (bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData); emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Move value of _settingId from pending variable to setting variable * @param _settingId The ID of the setting * @param _settingType The type of the setting */ function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal { // If settingType == uint256 if (_settingType == 1) { _aoUintSetting.movePendingToSetting(_settingId); } else if (_settingType == 2) { // Else if settingType == bool _aoBoolSetting.movePendingToSetting(_settingId); } else if (_settingType == 3) { // Else if settingType == address _aoAddressSetting.movePendingToSetting(_settingId); } else if (_settingType == 4) { // Else if settingType == bytes32 _aoBytesSetting.movePendingToSetting(_settingId); } else { // Else if settingType == string _aoStringSetting.movePendingToSetting(_settingId); } } } /** * @title AOEarning * * This contract stores the earning from staking/hosting content on AO */ contract AOEarning is TheAO { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; address public baseDenominationAddress; address public treasuryAddress; address public nameFactoryAddress; address public pathosAddress; address public ethosAddress; bool public paused; bool public killed; AOToken internal _baseAO; AOTreasury internal _treasury; NameFactory internal _nameFactory; Pathos internal _pathos; Ethos internal _ethos; AOSetting internal _aoSetting; // Total earning from staking content from all nodes uint256 public totalStakeContentEarning; // Total earning from hosting content from all nodes uint256 public totalHostContentEarning; // Total The AO earning uint256 public totalTheAOEarning; // Mapping from address to his/her earning from content that he/she staked mapping (address => uint256) public stakeContentEarning; // Mapping from address to his/her earning from content that he/she hosted mapping (address => uint256) public hostContentEarning; // Mapping from address to his/her network price earning // i.e, when staked amount = filesize mapping (address => uint256) public networkPriceEarning; // Mapping from address to his/her content price earning // i.e, when staked amount > filesize mapping (address => uint256) public contentPriceEarning; // Mapping from address to his/her inflation bonus mapping (address => uint256) public inflationBonusAccrued; struct Earning { bytes32 purchaseId; uint256 paymentEarning; uint256 inflationBonus; uint256 pathosAmount; uint256 ethosAmount; } // Mapping from address to earning from staking content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public stakeEarnings; // Mapping from address to earning from hosting content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public hostEarnings; // Mapping from purchase ID to earning for The AO mapping (bytes32 => Earning) public theAOEarnings; // Mapping from stake ID to it's total earning from staking mapping (bytes32 => uint256) public totalStakedContentStakeEarning; // Mapping from stake ID to it's total earning from hosting mapping (bytes32 => uint256) public totalStakedContentHostEarning; // Mapping from stake ID to it's total earning earned by The AO mapping (bytes32 => uint256) public totalStakedContentTheAOEarning; // Mapping from content host ID to it's total earning mapping (bytes32 => uint256) public totalHostContentEarningById; // Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earning is released from escrow // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when host's Name earns Ethos when a node buys a content event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _nameFactoryAddress The address of NameFactory * @param _pathosAddress The address of Pathos * @param _ethosAddress The address of Ethos */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; pathosAddress = _pathosAddress; ethosAddress = _ethosAddress; _aoSetting = AOSetting(_aoSettingAddress); _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _nameFactory = NameFactory(_nameFactoryAddress); _pathos = Pathos(_pathosAddress); _ethos = Ethos(_ethosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Calculate the content creator/host/The AO earning when request node buys the content. * Also at this stage, all of the earnings are stored in escrow * @param _buyer The request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function calculateEarning( address _buyer, bytes32 _purchaseId, uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) public isContractActive inWhitelist returns (bool) { // Split the payment earning between content creator and host and store them in escrow _escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); // Calculate the inflation bonus earning for content creator/node/The AO in escrow _escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); return true; } /** * @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID to check * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _stakeOwner The address of the stake owner * @param _host The address of the node that host the file * @return true on success */ function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) { // Release the earning in escrow for stake owner _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0); // Release the earning in escrow for host _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1); // Release the earning in escrow for The AO _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2); return true; } /***** INTERNAL METHODS *****/ /** * @dev Calculate the payment split for content creator/host and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal { (uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType); (uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning); _escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount); } /** * @dev Calculate the inflation bonus amount * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @return the bonus network amount */ function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); return _networkBonus.add(_primordialBonus); } /** * @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _inflationBonusAmount The amount of inflation bonus earning * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowInflationBonus( bytes32 _purchaseId, uint256 _inflationBonusAmount, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) internal { (, uint256 theAOCut,) = _getSettingVariables(); if (_inflationBonusAmount > 0) { // Store how much the content creator earns in escrow uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.inflationBonus = _stakeOwnerInflationBonus; require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus)); emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0); // Store how much the host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus); require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus)); emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1); // Store how much the The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus)); emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2); } else { emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0); emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1); emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2); } } /** * @dev Release the escrowed earning for a specific purchase ID for an account * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _account The address of account that made the earning (content creator/host) * @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO) */ function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal { // Make sure the recipient type is valid require (_recipientType >= 0 && _recipientType <= 2); uint256 _paymentEarning; uint256 _inflationBonus; uint256 _totalEarning; uint256 _pathosAmount; uint256 _ethosAmount; if (_recipientType == 0) { Earning storage _earning = stakeEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _pathosAmount = _earning.pathosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning); stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning); totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the content creator/stake owner with some Pathos require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount)); emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount); } else if (_recipientType == 1) { _earning = hostEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _ethosAmount = _earning.ethosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalHostContentEarning = totalHostContentEarning.add(_totalEarning); hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning); totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning); totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the host node with some Ethos require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount)); emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount); } else { _earning = theAOEarnings[_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalTheAOEarning = totalTheAOEarning.add(_totalEarning); inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning); } require (_baseAO.unescrowFrom(_account, _totalEarning)); emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType); } /** * @dev Get setting variables * @return inflationRate The rate to use when calculating inflation bonus * @return theAOCut The rate to use when calculating the AO earning * @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO */ function _getSettingVariables() internal view returns (uint256, uint256, uint256) { (uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate'); (uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut'); (uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate'); return (inflationRate, theAOCut, theAOEthosEarnedRate); } /** * @dev Calculate the payment split for content creator and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @return The stake owner's earning amount * @return The pathos earned from this transaction */ function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) { (uint256 inflationRate,,) = _getSettingVariables(); Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.purchaseId = _purchaseId; // Store how much the content creator (stake owner) earns in escrow // If content is AO Content Usage Type, stake owner earns 0% // and all profit goes to the serving host node _stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; // Pathos = Price X Node Share X Inflation Rate _stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning)); emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0); return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount); } /** * @dev Calculate the payment split for host node and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _host The address of the host node * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @param _stakeOwnerEarning The stake owner's earning amount * @return The ethos earned from this transaction */ function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); // Store how much the node host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.purchaseId = _purchaseId; _hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning); // Ethos = Price X Creator Share X Inflation Rate _hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); if (_isAOContentUsageType) { require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning)); } else { // If not AO Content usage type, we want to mint to the host require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning)); } emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1); return _hostEarning.ethosAmount; } /** * @dev Calculate the earning for The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _pathosAmount The amount of pathos earned by stake owner * @param _ethosAmount The amount of ethos earned by host node */ function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal { (,,uint256 theAOEthosEarnedRate) = _getSettingVariables(); // Store how much The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.purchaseId = _purchaseId; // Pathos + X% of Ethos _theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR())); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning)); emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2); } } /** * @title AOContent * * The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens * on his/her content */ contract AOContent is TheAO { using SafeMath for uint256; uint256 public totalContents; uint256 public totalContentHosts; uint256 public totalStakedContents; uint256 public totalPurchaseReceipts; address public settingTAOId; address public baseDenominationAddress; address public treasuryAddress; AOToken internal _baseAO; AOTreasury internal _treasury; AOEarning internal _earning; AOSetting internal _aoSetting; NameTAOPosition internal _nameTAOPosition; bool public paused; bool public killed; struct Content { bytes32 contentId; address creator; /** * baseChallenge is the content's PUBLIC KEY * When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY) * so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node * submit */ string baseChallenge; uint256 fileSize; bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content address taoId; bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO uint8 updateTAOContentStateV; bytes32 updateTAOContentStateR; bytes32 updateTAOContentStateS; string extraData; } struct StakedContent { bytes32 stakeId; bytes32 contentId; address stakeOwner; uint256 networkAmount; // total network token staked in base denomination uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination) uint256 primordialWeightedMultiplier; uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000 bool active; // true if currently staked, false when unstaked uint256 createdOnTimestamp; } struct ContentHost { bytes32 contentHostId; bytes32 stakeId; address host; /** * encChallenge is the content's PUBLIC KEY unique to the host */ string encChallenge; string contentDatKey; string metadataDatKey; } struct PurchaseReceipt { bytes32 purchaseId; bytes32 contentHostId; address buyer; uint256 price; uint256 amountPaidByBuyer; // total network token paid in base denomination uint256 amountPaidByAO; // total amount paid by AO string publicKey; // The public key provided by request node address publicAddress; // The public address provided by request node uint256 createdOnTimestamp; } // Mapping from Content index to the Content object mapping (uint256 => Content) internal contents; // Mapping from content ID to index of the contents list mapping (bytes32 => uint256) internal contentIndex; // Mapping from StakedContent index to the StakedContent object mapping (uint256 => StakedContent) internal stakedContents; // Mapping from stake ID to index of the stakedContents list mapping (bytes32 => uint256) internal stakedContentIndex; // Mapping from ContentHost index to the ContentHost object mapping (uint256 => ContentHost) internal contentHosts; // Mapping from content host ID to index of the contentHosts list mapping (bytes32 => uint256) internal contentHostIndex; // Mapping from PurchaseReceipt index to the PurchaseReceipt object mapping (uint256 => PurchaseReceipt) internal purchaseReceipts; // Mapping from purchase ID to index of the purchaseReceipts list mapping (bytes32 => uint256) internal purchaseReceiptIndex; // Mapping from buyer's content host ID to the buy ID // To check whether or not buyer has bought/paid for a content mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts; // Event to be broadcasted to public when `content` is stored event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType); // Event to be broadcasted to public when `stakeOwner` stakes a new content event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp); // Event to be broadcasted to public when a node hosts a content event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey); // Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage); // Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier); // Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId); // Event to be broadcasted to public when `stakeOwner` re-stakes an existing content event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier); // Event to be broadcasted to public when a request node buys a content event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp); // Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _earningAddress The address of AOEarning * @param _nameTAOPositionAddress The address of NameTAOPosition */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public { settingTAOId = _settingTAOId; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; nameTAOPositionAddress = _nameTAOPositionAddress; _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _earning = AOEarning(_earningAddress); _aoSetting = AOSetting(_aoSettingAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge */ function stakeAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage)); (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_aoContent, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _profitPercentage ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file */ function stakeCreativeCommonsContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize); (,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_creativeCommons, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) */ function stakeTAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, address _taoId) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require ( _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize && _nameTAOPosition.senderIsPosition(msg.sender, _taoId) ); (,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_taoContent, _taoId ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Set profit percentage on existing staked content * Will throw error if this is a Creative Commons/T(AO) Content * @param _stakeId The ID of the staked content * @param _profitPercentage The new value to be set */ function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive { require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR()); // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure we are updating profit percentage for AO Content only // Creative Commons/T(AO) Content has 0 profit percentage require (_isAOContentUsageType(_stakedContent.contentId)); _stakedContent.profitPercentage = _profitPercentage; emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage); } /** * @dev Set extra data on existing content * @param _contentId The ID of the content * @param _extraData some extra information to send to the contract for a content */ function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); Content storage _content = contents[contentIndex[_contentId]]; // Make sure the content creator is the same as the sender require (_content.creator == msg.sender); _content.extraData = _extraData; } /** * @dev Return content info at a given ID * @param _contentId The ID of the content * @return address of the creator * @return file size of the content * @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @return The TAO ID for this content (if this is a T(AO) Content) * @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO * @return The V part of signature that is used to update the TAO Content State * @return The R part of signature that is used to update the TAO Content State * @return The S part of signature that is used to update the TAO Content State * @return the extra information sent to the contract when creating a content */ function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) { // Make sure the content exist require (contentIndex[_contentId] > 0); Content memory _content = contents[contentIndex[_contentId]]; return ( _content.creator, _content.fileSize, _content.contentUsageType, _content.taoId, _content.taoContentState, _content.updateTAOContentStateV, _content.updateTAOContentStateR, _content.updateTAOContentStateS, _content.extraData ); } /** * @dev Return content host info at a given ID * @param _contentHostId The ID of the hosted content * @return The ID of the staked content * @return address of the host * @return the dat key of the content * @return the dat key of the content's metadata */ function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; return ( _contentHost.stakeId, _contentHost.host, _contentHost.contentDatKey, _contentHost.metadataDatKey ); } /** * @dev Return staked content information at a given ID * @param _stakeId The ID of the staked content * @return The ID of the content being staked * @return address of the staked content's owner * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the profit percentage of the content * @return status of the staked content * @return the timestamp when the staked content was created */ function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; return ( _stakedContent.contentId, _stakedContent.stakeOwner, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.active, _stakedContent.createdOnTimestamp ); } /** * @dev Unstake existing staked content and refund partial staked amount to the stake owner * Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to * the mininum required to pay the fileSize * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to unstake * @param _networkFractionAmount The fraction amount of network token to unstake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to unstake */ function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the staked content has enough balance to unstake require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize)); if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount); require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount); require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Unstake existing staked content and refund the total staked amount to the stake owner * @param _stakeId The ID of the staked content */ function unstakeContent(bytes32 _stakeId) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); _stakedContent.active = false; if (_stakedContent.networkAmount > 0) { uint256 _unstakeNetworkAmount = _stakedContent.networkAmount; _stakedContent.networkAmount = 0; require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_stakedContent.primordialAmount > 0) { uint256 _primordialAmount = _stakedContent.primordialAmount; uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier; _stakedContent.primordialAmount = 0; _stakedContent.primordialWeightedMultiplier = 0; require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier)); } emit UnstakeContent(_stakedContent.stakeOwner, _stakeId); } /** * @dev Stake existing content with more tokens (this is to increase the price) * * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier) */ function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount)); // Make sure we can stake primordial token // If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier` // i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) { require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier); } _stakedContent.active = true; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount); require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount); // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Determine the content price hosted by a host * @param _contentHostId The content host ID to be checked * @return the price of the content */ function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) { // Make sure content host exist require (contentHostIndex[_contentHostId] > 0); bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure content is currently staked require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); return _stakedContent.networkAmount.add(_stakedContent.primordialAmount); } /** * @dev Determine the how much the content is paid by AO given a contentHostId * @param _contentHostId The content host ID to be checked * @return the amount paid by AO */ function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) { bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; if (_isAOContentUsageType(_contentId)) { return 0; } else { return contentHostPrice(_contentHostId); } } /** * @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content * @param _contentHostId The ID of hosted content * @param _networkIntegerAmount The integer amount of network token to pay * @param _networkFractionAmount The fraction amount of network token to pay * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _publicKey The public key of the request node * @param _publicAddress The public address of the request node */ function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); // Make sure public key is not empty require (bytes(_publicKey).length > 0); // Make sure public address is valid require (_publicAddress != address(0)); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]]; // Make sure the content currently has stake require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the buyer has not bought this content previously require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0); // Make sure the token amount can pay for the content price if (_isAOContentUsageType(_stakedContent.contentId)) { require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination)); } // Increment totalPurchaseReceipts; totalPurchaseReceipts++; // Generate purchaseId bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId)); PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts]; // Make sure the node doesn't buy the same content twice require (_purchaseReceipt.buyer == address(0)); _purchaseReceipt.purchaseId = _purchaseId; _purchaseReceipt.contentHostId = _contentHostId; _purchaseReceipt.buyer = msg.sender; // Update the receipt with the correct network amount _purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount); _purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId); _purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO); _purchaseReceipt.publicKey = _publicKey; _purchaseReceipt.publicAddress = _publicAddress; _purchaseReceipt.createdOnTimestamp = now; purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts; buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId; // Calculate content creator/host/The AO earning from this purchase and store them in escrow require (_earning.calculateEarning( msg.sender, _purchaseId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.stakeOwner, _contentHost.host, _isAOContentUsageType(_stakedContent.contentId) )); emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp); } /** * @dev Return purchase receipt info at a given ID * @param _purchaseId The ID of the purchased content * @return The ID of the content host * @return address of the buyer * @return price of the content * @return amount paid by AO * @return amount paid by Buyer * @return request node's public key * @return request node's public address * @return created on timestamp */ function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; return ( _purchaseReceipt.contentHostId, _purchaseReceipt.buyer, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp ); } /** * @dev Request node wants to become a distribution node after buying the content * Also, if this transaction succeeds, contract will release all of the earnings that are * currently in escrow for content creator/host/The AO */ function becomeHost( bytes32 _purchaseId, uint8 _baseChallengeV, bytes32 _baseChallengeR, bytes32 _baseChallengeS, string _encChallenge, string _contentDatKey, string _metadataDatKey ) public isContractActive { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; // Make sure the purchase receipt owner is the same as the sender require (_purchaseReceipt.buyer == msg.sender); // Verify that the file is not tampered by validating the base challenge signature // The signed base challenge key should match the one from content creator Content memory _content = contents[contentIndex[_contentId]]; require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress); _hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey); // Release earning from escrow require (_earning.releaseEarning( _stakeId, _purchaseReceipt.contentHostId, _purchaseId, (_purchaseReceipt.amountPaidByBuyer > _content.fileSize), stakedContents[stakedContentIndex[_stakeId]].stakeOwner, contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host) ); } /** * @dev Update the TAO Content State of a T(AO) Content * @param _contentId The ID of the Content * @param _taoId The ID of the TAO that initiates the update * @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO * @param _updateTAOContentStateV The V part of the signature for this update * @param _updateTAOContentStateR The R part of the signature for this update * @param _updateTAOContentStateS The S part of the signature for this update */ function updateTAOContentState( bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _updateTAOContentStateV, bytes32 _updateTAOContentStateR, bytes32 _updateTAOContentStateS ) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); require (AOLibrary.isTAO(_taoId)); (,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables(); require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO); address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS); Content storage _content = contents[contentIndex[_contentId]]; // Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId)); require (_content.contentUsageType == _contentUsageType_taoContent); _content.taoContentState = _taoContentState; _content.updateTAOContentStateV = _updateTAOContentStateV; _content.updateTAOContentStateR = _updateTAOContentStateR; _content.updateTAOContentStateS = _updateTAOContentStateS; emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState); } /***** INTERNAL METHODS *****/ /** * @dev Store the content information (content creation during staking) * @param _creator the address of the content creator * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _fileSize The size of the file * @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) * @return the ID of the content */ function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) { // Increment totalContents totalContents++; // Generate contentId bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents)); Content storage _content = contents[totalContents]; // Make sure the node does't store the same content twice require (_content.creator == address(0)); (,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables(); _content.contentId = _contentId; _content.creator = _creator; _content.baseChallenge = _baseChallenge; _content.fileSize = _fileSize; _content.contentUsageType = _contentUsageType; // If this is a TAO Content if (_contentUsageType == contentUsageType_taoContent) { _content.taoContentState = taoContentState_submitted; _content.taoId = _taoId; } contentIndex[_contentId] = totalContents; emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType); return _content.contentId; } /** * @dev Add the distribution node info that hosts the content * @param _host the address of the host * @param _stakeId The ID of the staked content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata */ function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal { require (bytes(_encChallenge).length > 0); require (bytes(_contentDatKey).length > 0); require (bytes(_metadataDatKey).length > 0); require (stakedContentIndex[_stakeId] > 0); // Increment totalContentHosts totalContentHosts++; // Generate contentId bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId)); ContentHost storage _contentHost = contentHosts[totalContentHosts]; // Make sure the node doesn't host the same content twice require (_contentHost.host == address(0)); _contentHost.contentHostId = _contentHostId; _contentHost.stakeId = _stakeId; _contentHost.host = _host; _contentHost.encChallenge = _encChallenge; _contentHost.contentDatKey = _contentDatKey; _contentHost.metadataDatKey = _metadataDatKey; contentHostIndex[_contentHostId] = totalContentHosts; emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey); } /** * @dev actual staking the content * @param _stakeOwner the address that stake the content * @param _contentId The ID of the content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return the newly created staked content ID */ function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) { // Increment totalStakedContents totalStakedContents++; // Generate stakeId bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId)); StakedContent storage _stakedContent = stakedContents[totalStakedContents]; // Make sure the node doesn't stake the same content twice require (_stakedContent.stakeOwner == address(0)); _stakedContent.stakeId = _stakeId; _stakedContent.contentId = _contentId; _stakedContent.stakeOwner = _stakeOwner; _stakedContent.profitPercentage = _profitPercentage; _stakedContent.active = true; _stakedContent.createdOnTimestamp = now; stakedContentIndex[_stakeId] = totalStakedContents; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { _stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _primordialAmount; // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp); return _stakedContent.stakeId; } /** * @dev Get setting variables * @return contentUsageType_aoContent Content Usage Type = AO Content * @return contentUsageType_creativeCommons Content Usage Type = Creative Commons * @return contentUsageType_taoContent Content Usage Type = T(AO) Content * @return taoContentState_submitted TAO Content State = Submitted * @return taoContentState_pendingReview TAO Content State = Pending Review * @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO */ function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) { (,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent'); (,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons'); (,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent'); (,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted'); (,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview'); (,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO'); return ( contentUsageType_aoContent, contentUsageType_creativeCommons, contentUsageType_taoContent, taoContentState_submitted, taoContentState_pendingReview, taoContentState_acceptedToTAO ); } /** * @dev Check whether or not the content is of AO Content Usage Type * @param _contentId The ID of the content * @return true if yes. false otherwise */ function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) { (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent; } } /** * @title Name */ contract Name is TAO { /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress) TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public { // Creating Name typeId = 1; } } contract Logos is TAOCurrency { NameTAOPosition internal _nameTAOPosition; // Mapping of a Name ID to the amount of Logos positioned by others to itself // address is the address of nameId, not the eth public address mapping (address => uint256) public positionFromOthers; // Mapping of Name ID to other Name ID and the amount of Logos positioned by itself mapping (address => mapping(address => uint256)) public positionToOthers; // Mapping of a Name ID to the total amount of Logos positioned by itself to others mapping (address => uint256) public totalPositionToOthers; // Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned mapping (address => mapping(address => uint256)) public advocatedTAOLogos; // Mapping of a Name ID to the total amount of Logos earned from advocated TAO mapping (address => uint256) public totalAdvocatedTAOLogos; // Event broadcasted to public when `from` address position `value` Logos to `to` event PositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `from` address unposition `value` Logos from `to` event UnpositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId` event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount); // Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId` event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress) TAOCurrency(initialSupply, tokenName, tokenSymbol) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of _id */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Get the total sum of Logos for an address * @param _target The address to check * @return The total sum of Logos (own + positioned + advocated TAOs) */ function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) { return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]); } /** * @dev `_from` Name position `_value` Logos onto `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to position * @return true on success */ function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't position Logos to itself require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value); positionFromOthers[_to] = positionFromOthers[_to].add(_value); emit PositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers); assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance); return true; } /** * @dev `_from` Name unposition `_value` Logos from `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to unposition * @return true on success */ function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't unposition Logos to itself require (positionToOthers[_from][_to] >= _value); uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value); positionFromOthers[_to] = positionFromOthers[_to].sub(_value); emit UnpositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers); assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance); return true; } /** * @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate * @param _taoId The ID of the advocated TAO * @param _amount the amount to reward * @return true on success */ function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) { require (_amount > 0); address _nameId = _nameTAOPosition.getAdvocate(_taoId); advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount); emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount); return true; } /** * @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId` * @param _fromNameId The ID of the Name that sends the Logos * @param _toNameId The ID of the Name that receives the Logos * @param _taoId The ID of the advocated TAO * @return true on success */ function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) { require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId)); require (advocatedTAOLogos[_fromNameId][_taoId] > 0); require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]); uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId]; advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount); totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount); advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount); emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount); return true; } } /** * @title AOLibrary */ library AOLibrary { using SafeMath for uint256; uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1 uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000 /** * @dev Check whether or not the given TAO ID is a TAO * @param _taoId The ID of the TAO * @return true if yes. false otherwise */ function isTAO(address _taoId) public view returns (bool) { return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0); } /** * @dev Check whether or not the given Name ID is a Name * @param _nameId The ID of the Name * @return true if yes. false otherwise */ function isName(address _nameId) public view returns (bool) { return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate * @param _sender The address to check * @param _theAO The AO address * @param _nameTAOPositionAddress The address of NameTAOPosition * @return true if yes, false otherwise */ function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { return (_sender == _theAO || ( (isTAO(_theAO) || isName(_theAO)) && _nameTAOPositionAddress != address(0) && NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO) ) ); } /** * @dev Return the divisor used to correctly calculate percentage. * Percentage stored throughout AO contracts covers 4 decimals, * so 1% is 10000, 1.25% is 12500, etc */ function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; } /** * @dev Return the divisor used to correctly calculate multiplier. * Multiplier stored throughout AO contracts covers 6 decimals, * so 1 is 1000000, 0.023 is 23000, etc */ function MULTIPLIER_DIVISOR() public pure returns (uint256) { return _MULTIPLIER_DIVISOR; } /** * @dev Check whether or not content creator can stake a content based on the provided params * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return true if yes. false otherwise */ function canStake(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public view returns (bool) { return ( bytes(_baseChallenge).length > 0 && bytes(_encChallenge).length > 0 && bytes(_contentDatKey).length > 0 && bytes(_metadataDatKey).length > 0 && _fileSize > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) && _stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true && _profitPercentage <= _PERCENTAGE_DIVISOR ); } /** * @dev Check whether or the requested unstake amount is valid * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @param _stakedNetworkAmount The current staked network token amount * @param _stakedPrimordialAmount The current staked primordial token amount * @param _stakedFileSize The file size of the staked content * @return true if can unstake, false otherwise */ function canUnstakePartial( address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _stakedNetworkAmount, uint256 _stakedPrimordialAmount, uint256 _stakedFileSize) public view returns (bool) { if ( (_denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && _stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) ) || _stakedPrimordialAmount < _primordialAmount || ( _denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize) ) || ( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize) ) { return false; } else { return true; } } /** * @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _isAOContentUsageType whether or not the content is of AO Content usage type * @param _fileSize The size of the file * @param _stakedAmount The total staked amount * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @return true when the amount is sufficient, false otherwise */ function canStakeExisting( address _treasuryAddress, bool _isAOContentUsageType, uint256 _fileSize, uint256 _stakedAmount, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount ) public view returns (bool) { if (_isAOContentUsageType) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize; } else { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize; } } /** * @dev Check whether the network token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _price The price of the content * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @return true when the amount is sufficient, false otherwise */ function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price; } /** * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _currentPrimordialBalance Account's current primordial token balance * @param _additionalWeightedMultiplier The weighted multiplier to be added * @param _additionalPrimordialAmount The primordial token amount to be added * @return the new primordial weighted multiplier */ function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedTokens.div(_totalTokens); } else { return _additionalWeightedMultiplier; } } /** * @dev Return the address that signed the message when a node wants to become a host * @param _callingContractAddress the address of the calling contract * @param _message the message that was signed * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the address that signed the TAO content state update * @param _callingContractAddress the address of the calling contract * @param _contentId the ID of the content * @param _taoId the ID of the TAO * @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the staking and earning information of a stake ID * @param _contentAddress The address of AOContent * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId); (uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier, totalStakeEarning, totalHostEarning, totalTheAOEarning ); } /** * @dev Return the staking information of a stake ID * @param _contentAddress The address of AOContent * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content */ function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { (,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier ); } /** * @dev Return the earning information of a stake ID * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { return ( AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId) ); } /** * @dev Calculate the primordial token multiplier on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Multiplier = S * Ending Multiplier = E * To Purchase = P * Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting multiplier in (10 ** 6) * @param _endingMultiplier The ending multiplier in (10 ** 6) * @return The multiplier in (10 ** 6) */ function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * Multiplier = (1 - (temp / T)) x (S-E) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals * so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E) * Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR * Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR * Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation * Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E) */ uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)); /** * Since _startingMultiplier and _endingMultiplier are in 6 decimals * Need to divide multiplier by _MULTIPLIER_DIVISOR */ return multiplier.div(_MULTIPLIER_DIVISOR); } else { return 0; } } /** * @dev Calculate the bonus percentage of network token on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Network Token Bonus Multiplier = Bs * Ending Network Token Bonus Multiplier = Be * To Purchase = P * AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * B% = (1 - (temp / T)) x (Bs-Be) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals * so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be) * B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR * B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR * Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) * But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR */ uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR); return bonusPercentage; } else { return 0; } } /** * @dev Calculate the bonus amount of network token on a given lot * AO Bonus Amount = B% x P * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier); /** * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR * when calculating the network token bonus amount */ uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR); return networkTokenBonus; } /** * @dev Calculate the maximum amount of Primordial an account can burn * _primordialBalance = P * _currentWeightedMultiplier = M * _maximumMultiplier = S * _amountToBurn = B * B = ((S x P) - (P x M)) / S * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _maximumMultiplier The maximum multiplier of this account * @return The maximum burn amount */ function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier); } /** * @dev Calculate the new multiplier after burning primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToBurn = B * _newMultiplier = E * E = (P x M) / (P - B) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier */ function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn)); } /** * @dev Calculate the new multiplier after converting network token to primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToConvert = C * _newMultiplier = E * E = (P x M) / (P + C) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToConvert The amount of network token to convert * @return The new multiplier */ function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert)); } /** * @dev Get TAO Currency Balances given a nameId * @param _nameId The ID of the Name * @param _logosAddress The address of Logos * @param _ethosAddress The address of Ethos * @param _pathosAddress The address of Pathos * @return sum Logos balance of the Name ID * @return Ethos balance of the Name ID * @return Pathos balance of the Name ID */ function getTAOCurrencyBalances( address _nameId, address _logosAddress, address _ethosAddress, address _pathosAddress ) public view returns (uint256, uint256, uint256) { return ( Logos(_logosAddress).sumBalanceOf(_nameId), TAOCurrency(_ethosAddress).balanceOf(_nameId), TAOCurrency(_pathosAddress).balanceOf(_nameId) ); } /** * @dev Return the address that signed the data and nonce when validating signature * @param _callingContractAddress the address of the calling contract * @param _data the data that was signed * @param _nonce The signed uint256 nonce * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce)); return ecrecover(_hash, _v, _r, _s); } /***** Internal Methods *****/ /** * @dev Check whether the network token and/or primordial token is adequate to pay for the filesize * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _fileSize The size of the file * @return true when the amount is sufficient, false otherwise */ function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize; } } contract Epiphany is TheAO { string public what; string public when; string public why; string public who; address public where; string public aSign; string public logos; constructor() public { what = 'The AO'; when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.'; why = 'To Hear, See, and Speak the Human inside Humanity.'; who = 'You. Set the world, Free. – Truth'; aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf'; logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32'; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Set `where` value * @param _where The new value to be set */ function setWhere(address _where) public onlyTheAO { where = _where; } }
Add child TAO _taoId The TAO ID to be added to _childId The ID to be added to as child TAO/ If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected Otherwise, child TAO needs parent TAO approval
function addChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) onlyFactory returns (bool) { require (!isChild(_taoId, _childId)); Family storage _family = families[_taoId]; require (_family.childInternalIdLookup[_childId] == 0); _family.childInternalId++; _family.childInternalIdLookup[_childId] = _family.childInternalId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); Child storage _child = _family.children[_family.childInternalId]; _child.taoId = _childId; address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId); address _childAdvocate = _nameTAOPosition.getAdvocate(_childId); if (_taoAdvocate == _childAdvocate) { _family.totalChildren++; _child.approved = true; _child.connected = true; Family storage _childFamily = families[_childId]; _childFamily.parentId = _taoId; } emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce); return true; }
10,007,400
//Address: 0x239c7175a43c500255c4d3849c2ab2973d4384d5 //Contract name: Token //Balance: 0 Ether //Verification Date: 12/14/2017 //Transacion Count: 0 // CODE STARTS HERE pragma solidity ^0.4.15; /** * assert(2 + 2 is 4 - 1 thats 3) Quick Mafs */ library QuickMafs { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a * _b; assert(_a == 0 || c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b > 0); // Solidity automatically throws when dividing by 0 uint256 c = _a / _b; 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; } } /** * The ownable contract contains an owner address. This give us simple ownership privledges and can allow ownship transfer. */ contract Ownable { /** * The owner/admin of the contract */ address public owner; /** * Constructor for contract. Sets The contract creator to the default owner. */ function Ownable() public { owner = msg.sender; } /** * Modifier to apply to methods to restrict access to the owner */ modifier onlyOwner(){ require(msg.sender == owner); _; //Placeholder for method content } /** * Transfer the ownership to a new owner can only be done by the current owner. */ function transferOwnership(address _newOwner) public onlyOwner { //Only make the change if required if (_newOwner != address(0)) { owner = _newOwner; } } } /** * ERC Token Standard #20 Interface */ contract ERC20 { /** * Get the total token supply */ function totalSupply() public constant returns (uint256 _totalSupply); /** * Get the account balance of another account with address _owner */ function balanceOf(address _owner) public constant returns (uint256 balance); /** * Send _amount of tokens to address _to */ function transfer(address _to, uint256 _amount) public returns (bool success); /** * Send _amount of tokens from address _from to address _to */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); /** * Allow _spender to withdraw from your account, multiple times, up to the _amount. * If this function is called again it overwrites the current allowance with _amount. * this function is required for some DEX functionality */ function approve(address _spender, uint256 _amount) public returns (bool success); /** * Returns the amount which _spender is still allowed to withdraw from _owner */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining); /** * Triggered when tokens are transferred. */ event Transfer(address indexed _from, address indexed _to, uint256 _amount); /** * Triggered whenever approve(address _spender, uint256 _amount) is called. */ event Approval(address indexed _owner, address indexed _spender, uint256 _amount); } /** * The CTN Token */ contract Token is ERC20, Ownable { using QuickMafs for uint256; string public constant SYMBOL = "CTN"; string public constant NAME = "Crypto Trust Network"; uint8 public constant DECIMALS = 18; /** * Total supply of tokens */ uint256 totalTokens; /** * The initial supply of coins before minting */ uint256 initialSupply; /** * Balances for each account */ mapping(address => uint256) balances; /** * Whos allowed to withdrawl funds from which accounts */ mapping(address => mapping (address => uint256)) allowed; /** * If the token is tradable */ bool tradable; /** * The address to store the initialSupply */ address public vault; /** * If the coin can be minted */ bool public mintingFinished = false; /** * Event for when new coins are created */ event Mint(address indexed _to, uint256 _value); /** * Event that is fired when token sale is over */ event MintFinished(); /** * Tokens can now be traded */ event TradableTokens(); /** * Allows this coin to be traded between users */ modifier isTradable(){ require(tradable); _; } /** * If this coin can be minted modifier */ modifier canMint() { require(!mintingFinished); _; } /** * Initializing the token, setting the owner, initial supply & vault */ function Token() public { initialSupply = 4500000 * 1 ether; totalTokens = initialSupply; tradable = false; vault = 0x6e794AAA2db51fC246b1979FB9A9849f53919D1E; balances[vault] = balances[vault].add(initialSupply); //Set initial supply to the vault } /** * Obtain current total supply of CTN tokens */ function totalSupply() public constant returns (uint256 totalAmount) { totalAmount = totalTokens; } /** * Get the initial supply of CTN coins */ function baseSupply() public constant returns (uint256 initialAmount) { initialAmount = initialSupply; } /** * Returns the balance of a wallet */ function balanceOf(address _address) public constant returns (uint256 balance) { return balances[_address]; } /** * Transfer CTN between wallets */ function transfer(address _to, uint256 _amount) public isTradable returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } /** * Send _amount of tokens from address _from to address _to * The transferFrom method is used for a withdraw workflow, allowing contracts to send * tokens on your behalf, for example to "deposit" to a contract address and/or to charge * fees in sub-currencies; the command should fail unless the _from account has * deliberately authorized the sender of the message via some mechanism; we propose * these standardized APIs for approval: */ function transferFrom( address _from, address _to, uint256 _amount ) public isTradable returns (bool success) { var _allowance = allowed[_from][msg.sender]; /** * QuickMaf will roll back any changes so no need to check before these operations */ balances[_to] = balances[_to].add(_amount); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = _allowance.sub(_amount); Transfer(_from, _to, _amount); return true; } /** * Allows an address to transfer money out this is administered by the contract owner who can specify how many coins an account can take. * Needs to be called to feault the amount to 0 first -> https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function approve(address _spender, uint256 _amount) public returns (bool) { /** *Set the amount they are able to spend to 0 first so that transaction ordering cannot allow multiple withdrawls asyncly *This function always requires to calls if a user has an amount they can withdrawl. */ require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * Check the amount of tokens the owner has allowed to a spender */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Makes the coin tradable between users cannot be undone */ function makeTradable() public onlyOwner { tradable = true; TradableTokens(); } /** * Mint tokens to users */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalTokens = totalTokens.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * Function to stop minting tokens irreversable */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * The initial crowdsale of the token */ contract Sale is Ownable { using QuickMafs for uint256; /** * The hard cap of the token sale */ uint256 hardCap; /** * The soft cap of the token sale */ uint256 softCap; /** * The bonus cap for the token sale */ uint256 bonusCap; /** * How many tokens you get per ETH */ uint256 tokensPerETH; /** * //the start time of the sale (new Date("Dec 22 2017 18:00:00 GMT").getTime() / 1000) */ uint256 public start = 1513965600; /** * The end time of the sale (new Date("Jan 22 2018 18:00:00 GMT").getTime() / 1000) */ uint256 public end = 1516644000; /** * Two months after the sale ends used to retrieve unclaimed refunds (new Date("Mar 22 2018 18:00:00 GMT").getTime() / 1000) */ uint256 public twoMonthsLater = 1521741600; /** * Token for minting purposes */ Token public token; /** * The address to store eth in during sale */ address public vault; /** * How much ETH each user has sent to this contract. For softcap unmet refunds */ mapping(address => uint256) investments; /** * Every purchase during the sale */ event TokenSold(address recipient, uint256 etherAmount, uint256 ctnAmount, bool bonus); /** * Triggered when tokens are transferred. */ event PriceUpdated(uint256 amount); /** * Only make certain changes before the sale starts */ modifier isPreSale(){ require(now < start); _; } /** * Is the sale still on */ modifier isSaleOn() { require(now >= start && now <= end); _; } /** * Has the sale completed */ modifier isSaleFinished() { bool hitHardCap = token.totalSupply().sub(token.baseSupply()) >= hardCap; require(now > end || hitHardCap); _; } /** * Has the sale completed */ modifier isTwoMonthsLater() { require(now > twoMonthsLater); _; } /** * Make sure we are under the hardcap */ modifier isUnderHardCap() { bool underHard = token.totalSupply().sub(token.baseSupply()) <= hardCap; require(underHard); _; } /** * Make sure we are over the soft cap */ modifier isOverSoftCap() { bool overSoft = token.totalSupply().sub(token.baseSupply()) >= softCap; require(overSoft); _; } /** * Make sure we are over the soft cap */ modifier isUnderSoftCap() { bool underSoft = token.totalSupply().sub(token.baseSupply()) < softCap; require(underSoft); _; } /** * The token sale constructor */ function Sale() public { hardCap = 10500000 * 1 ether; softCap = 500000 * 1 ether; bonusCap = 2000000 * 1 ether; tokensPerETH = 536; //Tokens per 1 ETH token = new Token(); vault = 0x6e794AAA2db51fC246b1979FB9A9849f53919D1E; } /** * Fallback function which receives ether and created the appropriate number of tokens for the * msg.sender. */ function() external payable { createTokens(msg.sender); } /** * If the soft cap has not been reached and the sale is over investors can reclaim their funds */ function refund() public isSaleFinished isUnderSoftCap { uint256 amount = investments[msg.sender]; investments[msg.sender] = investments[msg.sender].sub(amount); msg.sender.transfer(amount); } /** * Withdrawl the funds from the contract. * Make the token tradeable and finish minting */ function withdrawl() public isSaleFinished isOverSoftCap { vault.transfer(this.balance); //Stop minting of the token and make the token tradeable token.finishMinting(); token.makeTradable(); } /** * Update the ETH price for the token sale */ function updatePrice(uint256 _newPrice) public onlyOwner isPreSale { tokensPerETH = _newPrice; PriceUpdated(_newPrice); } /** * Allows user to buy coins if we are under the hardcap also adds a bonus if under the bonus amount */ function createTokens(address recipient) public isUnderHardCap isSaleOn payable { uint256 amount = msg.value; uint256 tokens = tokensPerETH.mul(amount); bool bonus = false; if (token.totalSupply().sub(token.baseSupply()) < bonusCap) { bonus = true; tokens = tokens.add(tokens.div(5)); } //Add the amount to user invetment total investments[msg.sender] = investments[msg.sender].add(msg.value); token.mint(recipient, tokens); TokenSold(recipient, amount, tokens, bonus); } /** * Withdrawl the funds from the contract. * Make the token tradeable and finish minting */ function cleanup() public isTwoMonthsLater { vault.transfer(this.balance); token.finishMinting(); token.makeTradable(); } function destroy() public onlyOwner isTwoMonthsLater { token.finishMinting(); token.makeTradable(); token.transferOwnership(owner); selfdestruct(vault); } /** * Get the ETH balance of this contract */ function getBalance() public constant returns (uint256 totalAmount) { totalAmount = this.balance; } }
Function to stop minting tokens irreversable/
function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; }
2,492,944
pragma solidity ^0.4.23; /*************************************************** Externally copied contracts and interfaces. Source: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/ERC20Basic.sol ***************************************************/ /**** ERC20Basic.sol ****/ /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /**** ERC20Basic.sol ****/ /**** ERC20.sol ****/ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /**** ERC20.sol ****/ /**** SafeMath.sol ****/ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /**** SafeMath.sol ****/ /**** Ownable.sol ****/ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /**** Ownable.sol ****/ /*************************************************** * Individually implemented code ***************************************************/ /** * @title UChain ERC20 Token */ contract UChainToken is ERC20 { using SafeMath for uint256; /* Constant variables of the token */ string constant public name = 'UChain Token'; string constant public symbol = 'UCN'; uint8 constant public decimals = 18; uint256 constant public decimalFactor = 10 ** uint(decimals); uint256 public totalSupply; /* minting related state */ bool public isMintingFinished = false; mapping(address => bool) public admins; /* vesting related state */ struct Vesting { uint256 vestedUntil; uint256 vestedAmount; } mapping(address => Vesting) public vestingEntries; /* ERC20 related state */ bool public isTransferEnabled = false; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowances; /* custom events */ event MintFinished(); event Mint(address indexed _beneficiary, uint256 _value); event MintVested(address indexed _beneficiary, uint256 _value); event AdminRemoved(address indexed _adminAddress); event AdminAdded(address indexed _adminAddress); /** * @dev contstructor. */ constructor() public { admins[msg.sender] = true; } /*************************************************** * View only methods ***************************************************/ /** * @dev specified in the ERC20 interface, returns the total token supply. Burned tokens are not counted. */ function totalSupply() public view returns (uint256) { return totalSupply - balances[address(0)]; } /** * @dev Get the token balance for token owner * @param _tokenOwner The address of you want to query the balance for */ function balanceOf(address _tokenOwner) public view returns (uint256) { return balances[_tokenOwner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _tokenOwner 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 _tokenOwner, address _spender) public view returns (uint256) { return allowances[_tokenOwner][_spender]; } /*************************************************** * Admin permission related methods ***************************************************/ /** * @dev Throws if called by any account other than the owner. */ modifier onlyAdmin() { require(admins[msg.sender]); _; } /** * @dev remove admin rights * @param _adminAddress address to remove from admin list */ function removeAdmin(address _adminAddress) public onlyAdmin { delete admins[_adminAddress]; emit AdminRemoved(_adminAddress); } /** * @dev give admin rights to address * @param _adminAddress address to add to admin list */ function addAdmin(address _adminAddress) public onlyAdmin { admins[_adminAddress] = true; emit AdminAdded(_adminAddress); } /** * @dev tells you whether a particular address has admin privileges or not * @param _adminAddress address to check whether it has admin privileges */ function isAdmin(address _adminAddress) public view returns (bool) { return admins[_adminAddress]; } /*************************************************** * Minting related methods ***************************************************/ function mint(address _beneficiary, uint256 _value) public onlyAdmin returns (bool) { require(!isMintingFinished); totalSupply = totalSupply.add(_value); balances[_beneficiary] = balances[_beneficiary].add(_value); emit Mint(_beneficiary, _value); emit Transfer(address(0), _beneficiary, _value); return true; } function bulkMint(address[] _beneficiaries, uint256[] _values) public onlyAdmin returns (bool) { require(_beneficiaries.length == _values.length); for (uint256 i = 0; i < _beneficiaries.length; i = i.add(1)) { require(mint(_beneficiaries[i], _values[i])); } return true; } function mintVested(uint256 _vestedUntil, address _beneficiary, uint256 _value) public onlyAdmin returns (bool) { require(mint(_beneficiary, _value)); vestingEntries[_beneficiary] = Vesting(_vestedUntil, _value); emit MintVested(_beneficiary, _value); return true; } function bulkMintVested(uint256 _vestedUntil, address[] _beneficiaries, uint256[] _values) public onlyAdmin returns (bool) { require(_beneficiaries.length == _values.length); for (uint256 i = 0; i < _beneficiaries.length; i = i.add(1)) { require(mintVested(_vestedUntil, _beneficiaries[i], _values[i])); } return true; } /** * @dev finishes the minting. After this call no more tokens can be minted. */ function finishMinting() public onlyAdmin { isMintingFinished = true; } /*************************************************** * Vesting related methods ***************************************************/ function getNonVestedBalanceOf(address _tokenOwner) public view returns (uint256) { if (block.timestamp < vestingEntries[_tokenOwner].vestedUntil) { return balances[_tokenOwner].sub(vestingEntries[_tokenOwner].vestedAmount); } else { return balances[_tokenOwner]; } } /*************************************************** * Basic Token operations * Source: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/BasicToken.sol ***************************************************/ /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(isTransferEnabled); require(_to != address(0)); require(_value <= getNonVestedBalanceOf(msg.sender)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /*************************************************** * Standard Token operations * Source: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/StandardToken.sol ***************************************************/ /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(isTransferEnabled); require(_to != address(0)); require(_value <= getNonVestedBalanceOf(_from)); require(_value <= allowances[_from][msg.sender]); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev sets the right to transfer tokens or not. * @param _isTransferEnabled the new state to set */ function setIsTransferEnabled(bool _isTransferEnabled) public onlyAdmin { isTransferEnabled = _isTransferEnabled; } }
Transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
function transfer(address _to, uint256 _value) public returns (bool) { require(isTransferEnabled); require(_to != address(0)); require(_value <= getNonVestedBalanceOf(msg.sender)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
74,456
/* A simple Ethereum Virtual Machine Database (EVMDB). // // Used for creating/managing DBs on the EVM. // // Provides insert, update, delete and search functions. // The search is only exact search at the moment. // // Further developments may include type checking, "select" search, // complicated DB structues etc. // // See https://github.com/eyalron33/EVMDB/ for documentation // // License: MIT */ pragma solidity ^0.4.4; contract EVMDB { int256 constant NOT_FOUND = -1; struct DB { address owner; bytes32 name; bytes32[] header; bytes32[][] data; uint256[] primary_key; // Assume 'primary key' is the first column in 'data' } DB[] DBs; address god; function EVMDB() { god = msg.sender; } /* Events and Modifiers */ event DBCreated(bytes32 name, uint256 index); event RowInserted(uint256 db, uint256 row); event RowUpdated(uint256 db, uint256 row); event RowErased(uint256 db, uint256 row); modifier onlyGod { if (msg.sender != god) throw; _ ;} ///////////////////////////////////////////////// /// ... DB manipulation functions ... ///////////////////////////////////////////////// /// creates a new DB, and emits an event with the DB id. /// Primary key is *always* taken to be the first column. /// /// @param _name name of the DB /// @param _headers array (of any size) of DB header names /// /// @return id of newly created DB function create(bytes32 _name, bytes32[] _headers) external returns (uint256) { if (_name != "") { uint256 DB_id = DBs.length; uint256 i; //array extension is manual DBs.length = DB_id + 1; DBs[DB_id].header.length = _headers.length; for (i=0; i<_headers.length; i++) { DBs[DB_id].header[i] = _headers[i]; } DBs[DB_id].name = _name; DBs[DB_id].owner = msg.sender; DBCreated(_name, DB_id); return DB_id; } } /// inserts data to a new row in the DB /// /// @param _DB_id id of the DB /// @param _data data to insert /// /// @return id of newly created row function insert(uint256 _DB_id, bytes32[] _data) external returns (uint256) { if (_DB_id < DBs.length && msg.sender == DBs[_DB_id].owner && _data.length == DBs[_DB_id].header.length) { uint256 row_id = DBs[_DB_id].data.length; uint256 i; //array extension is manual DBs[_DB_id].data.length = row_id + 1; DBs[_DB_id].data[row_id].length = _data.length; for (i=0; i<_data.length; i++) { DBs[_DB_id].data[row_id][i] = _data[i]; } //push to primary_key table uint256 place = place_to_push(_DB_id, _data[0]); push_key(_DB_id, place, row_id); RowInserted(_DB_id, row_id); return row_id; } else { log1(bytes32(_DB_id),"invalid parameters"); } } /// updates a row in a DB /// /// @param _DB_id id of the DB /// @param _row number of row to update /// @param _data new data function update(uint256 _DB_id, uint256 _row, bytes32[] _data) external { //TODO: row_id --> row everywhere if (_DB_id < DBs.length && msg.sender == DBs[_DB_id].owner && _row < DBs[_DB_id].data.length && _data.length == DBs[_DB_id].header.length) { uint256 i; bool already_deleted = true; for (i=0; i<DBs[_DB_id].data[_row].length; i++) { if (DBs[_DB_id].data[_row][i] != 0) { already_deleted = false; } } //delete key if (!already_deleted) { int256 place = binary_search(_DB_id, DBs[_DB_id].data[_row][0]); delete_key(_DB_id, uint256(place)); } //update value for (i=0; i<_data.length; i++) { DBs[_DB_id].data[_row][i] = _data[i]; } //update key place = int256(place_to_push(_DB_id, _data[0])); push_key(_DB_id, uint256(place), _row); RowUpdated(_DB_id, _row); } else { log1(bytes32(_DB_id),"invalid parameters"); } } /// deletes a row from a DB /// /// @param _DB_id id of the DB /// @param _row number of row to delete function erase(uint256 _DB_id, uint256 _row) external { if (_DB_id < DBs.length && msg.sender == DBs[_DB_id].owner && _row < DBs[_DB_id].data.length) { uint256 i; bool already_deleted = true; for (i=0; i<DBs[_DB_id].data[_row].length; i++) { if (DBs[_DB_id].data[_row][i] != 0) { already_deleted = false; } } if (!already_deleted) { //delete key int256 place = binary_search(_DB_id, DBs[_DB_id].data[_row][0]); delete_key(_DB_id, uint256(place)); //delete from DB for (i=0; i<DBs[_DB_id].data[_row].length; i++) { delete DBs[_DB_id].data[_row][i]; } RowErased(_DB_id, _row); } else { log1(bytes32(_DB_id),"row already deleted"); } } else { log1(bytes32(_DB_id),"invalid parameters"); } } /// search a DB via primary key (which is assumed to be the first column) /// /// @param _DB_id id of the DB /// @param _value value to search function search(uint256 _DB_id, bytes32 _value) external constant returns (int256) { if (_DB_id < DBs.length) { int256 place = binary_search(_DB_id, _value); if (place > -1) { return int256(DBs[_DB_id].primary_key[uint256(place)]); } else { return place; } } else { return -1; } } ///////////////////////////////////////////////// /// ... Query DB functions ... ///////////////////////////////////////////////// /// Queries for header names /// /// @param _DB_id id of the DB /// /// @return array of header name function get_header(uint256 _DB_id) constant external returns (bytes32[]) { if (_DB_id < DBs.length) { return DBs[_DB_id].header; } else { bytes32[] memory temp; temp[0] = "invalid parameters"; return (temp); } } /// Queries for data by row number /// /// @param _DB_id id of the DB /// @param _row row number /// /// @return array consisting of row's items function get_row(uint256 _DB_id, uint256 _row) constant external returns (bytes32[]) { if (_DB_id < DBs.length && _row < DBs[_DB_id].data.length) { return (DBs[_DB_id].data[_row]); } else { bytes32[] memory temp; temp[0] = "invalid parameters"; return (temp); } } /// Queries for an item by row and column numbers /// /// @param _DB_id id of the DB /// @param _row row number /// @param _col column number /// /// @return item function get_row_col(uint256 _DB_id, uint256 _row, uint256 _col) constant external returns (bytes32) { if (_DB_id < DBs.length && _row < DBs[_DB_id].data.length && _col < DBs[_DB_id].header.length) { return (DBs[_DB_id].data[_row][_col]); } else { return ("invalid parameters"); } } /// Returns DB info: [owner, name, size], where size is #rows /// /// @param _DB_id id of the DB /// /// @return size of the DB function get_DB_info(uint256 _DB_id) constant external returns (address, bytes32, int256) { if (_DB_id < DBs.length) { return (DBs[_DB_id].owner, DBs[_DB_id].name, int256(DBs[_DB_id].data.length)); } else { return (0x0000000000000000000000000000000000000000,"DB_id not existing",-1); // error } } /// Queries for the number of DBs in the smart contract /// /// @return number of DBs function get_number_of_DBs() constant external returns (uint256) { return DBs.length; } ///////////////////////////////////////////////// /// ... Internal Functions ... ///////////////////////////////////////////////// // returns index of an element in a linked list or NOT_FOUND if not found function binary_search(uint256 DB_id, bytes32 data) internal returns (int256) { uint256 m=0; // search index //Using int256 as L may be -1, //this means that greatest searched index is 2^128-1, int256 L = 0; int256 R = int256(DBs[DB_id].primary_key.length)-1; while (L <= R) { m = uint256((L+R)/2); if (DBs[DB_id].data[DBs[DB_id].primary_key[m]][0] < data) { L = int256(m)+1; } else if (DBs[DB_id].data[DBs[DB_id].primary_key[m]][0] > data) { R = int256(m)-1; } else { return int256(m); } } return NOT_FOUND; } // returns a index to enter a new element (unlike searching, who returns a location of an existing element) function place_to_push(uint256 DB_id, bytes32 data) internal returns (uint256) { uint256 m=0; // search index //Using int256 as L may be -1, //this means that greatest searched index is 2^128-1, int256 L = 0; int256 R = int256(DBs[DB_id].primary_key.length)-1; while (L <= R) { m = uint256((L+R)/2); if (DBs[DB_id].data[DBs[DB_id].primary_key[m]][0] < data) { L = int256(m)+1; } else if (DBs[DB_id].data[DBs[DB_id].primary_key[m]][0] > data) { R = int256(m)-1; } else { return m; } } if ( (DBs[DB_id].primary_key.length>0) && (DBs[DB_id].data[DBs[DB_id].primary_key[m]][0] < data) ) return m+1; else return m; } function push_key(uint256 DB_id, uint256 place, uint256 new_value) internal { uint256 i; uint256 length = DBs[DB_id].primary_key.length + 1; DBs[DB_id].primary_key.length = length; //array extension is manual // push old key forward to make place for new one for (i=length-1; i>place; i--) { DBs[DB_id].primary_key[i] = DBs[DB_id].primary_key[i-1]; } DBs[DB_id].primary_key[place] = new_value; } function delete_key(uint256 DB_id, uint256 place) internal { uint256 i; uint256 length = DBs[DB_id].primary_key.length; for (i=place; i<length-1; i++) { DBs[DB_id].primary_key[i] = DBs[DB_id].primary_key[i+1]; } delete DBs[DB_id].primary_key[length-1]; DBs[DB_id].primary_key.length = length - 1; } }
inserts data to a new row in the DB _DB_id id of the DB _data data to insert return id of newly created rowarray extension is manual
function insert(uint256 _DB_id, bytes32[] _data) external returns (uint256) { if (_DB_id < DBs.length && msg.sender == DBs[_DB_id].owner && _data.length == DBs[_DB_id].header.length) { uint256 row_id = DBs[_DB_id].data.length; uint256 i; DBs[_DB_id].data.length = row_id + 1; DBs[_DB_id].data[row_id].length = _data.length; for (i=0; i<_data.length; i++) { DBs[_DB_id].data[row_id][i] = _data[i]; } push_key(_DB_id, place, row_id); RowInserted(_DB_id, row_id); return row_id; log1(bytes32(_DB_id),"invalid parameters"); } } msg.sender == DBs[_DB_id].owner && _row < DBs[_DB_id].data.length &&
6,387,010
./partial_match/42/0xd9153c72a6e1f6F362B13b6891B840e99AD46561/sources/NoFiPartyStarter.sol
Calculates if user's share of wETH in the pool is creater than their deposit amts (used for potential earnings) Accounting updates
function withdrawEarnings(address memberAddress, uint256 amount) external nonReentrant { uint256 initialTotalSharesAndLoot = totalShares.add(totalLoot); Member storage member = members[memberAddress]; uint256 sharesM = member.shares; uint256 lootM = member.loot; uint256 sharesAndLootM = sharesM.add(lootM); require(member.exists == true, "not member"); require(address(msg.sender) == memberAddress, "can only be called by member"); uint256 iTBVal = fairShare(userTokenBalances[GUILD][idleToken], sharesAndLootM, initialTotalSharesAndLoot); uint256 iBase = abs(totalDeposits).div(initialTotalSharesAndLoot).mul(sharesAndLootM).add(member.iTW); require(iTBVal.sub(iBase) >= amount, "not enough earnings to redeem this many tokens"); uint256 earningsToUser = subFees(GUILD, amount, address(idleToken)); uint256 redeemedTokens = amount; emit WithdrawEarnings(msg.sender, address(idleToken), earningsToUser, depositToken, redeemedTokens); member.iTW += amount; totalDeposits -= int(amount); unsafeInternalTransfer(GUILD, memberAddress, address(idleToken), earningsToUser); }
8,839,402
// File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 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 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 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _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 { require(account != address(0), "ERC20: mint to the zero address"); _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 { require(account != address(0), "ERC20: burn from the zero address"); _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 { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Initializable, Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; function initialize(address sender) public initializer { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is Initializable, ERC20, MinterRole { function initialize(address sender) public initializer { MinterRole.initialize(sender); } /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } // File: @aragon/court/contracts/lib/Checkpointing.sol pragma solidity ^0.5.8; /** * @title Checkpointing - Library to handle a historic set of numeric values */ library Checkpointing { uint256 private constant MAX_UINT192 = uint256(uint192(-1)); string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG"; string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE"; /** * @dev To specify a value at a given point in time, we need to store two values: * - `time`: unit-time value to denote the first time when a value was registered * - `value`: a positive numeric value to registered at a given point in time * * Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used * for it like block numbers, terms, etc. */ struct Checkpoint { uint64 time; uint192 value; } /** * @dev A history simply denotes a list of checkpoints */ struct History { Checkpoint[] history; } /** * @dev Add a new value to a history for a given point in time. This function does not allow to add values previous * to the latest registered value, if the value willing to add corresponds to the latest registered value, it * will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function add(History storage self, uint64 _time, uint256 _value) internal { require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG); _add192(self, _time, uint192(_value)); } /** * @dev Fetch the latest registered value of history, it will return zero if there was no value registered * @param self Checkpoints history to be queried */ function getLast(History storage self) internal view returns (uint256) { uint256 length = self.history.length; if (length > 0) { return uint256(self.history[length - 1].value); } return 0; } /** * @dev Fetch the most recent registered past value of a history based on a given point in time that is not known * how recent it is beforehand. It will return zero if there is no registered value or if given time is * previous to the first registered value. * It uses a binary search. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function get(History storage self, uint64 _time) internal view returns (uint256) { return _binarySearch(self, _time); } /** * @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero * if there is no registered value or if given time is previous to the first registered value. * It uses a linear search starting from the end. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function getRecent(History storage self, uint64 _time) internal view returns (uint256) { return _backwardsLinearSearch(self, _time); } /** * @dev Private function to add a new value to a history for a given point in time. This function does not allow to * add values previous to the latest registered value, if the value willing to add corresponds to the latest * registered value, it will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function _add192(History storage self, uint64 _time, uint192 _value) private { uint256 length = self.history.length; if (length == 0 || self.history[self.history.length - 1].time < _time) { // If there was no value registered or the given point in time is after the latest registered value, // we can insert it to the history directly. self.history.push(Checkpoint(_time, _value)); } else { // If the point in time given for the new value is not after the latest registered value, we must ensure // we are only trying to update the latest value, otherwise we would be changing past data. Checkpoint storage currentCheckpoint = self.history[length - 1]; require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE); currentCheckpoint.value = _value; } } /** * @dev Private function to execute a backwards linear search to find the most recent registered past value of a * history based on a given point in time. It will return zero if there is no registered value or if given time * is previous to the first registered value. Note that this function will be more suitable when we already know * that the time used to index the search is recent in the given history. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } uint256 index = length - 1; Checkpoint storage checkpoint = self.history[index]; while (index > 0 && checkpoint.time > _time) { index--; checkpoint = self.history[index]; } return checkpoint.time > _time ? 0 : uint256(checkpoint.value); } /** * @dev Private function execute a binary search to find the most recent registered past value of a history based on * a given point in time. It will return zero if there is no registered value or if given time is previous to * the first registered value. Note that this function will be more suitable when don't know how recent the * time used to index may be. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _binarySearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } // If the requested time is equal to or after the time of the latest registered value, return latest value uint256 lastIndex = length - 1; if (_time >= self.history[lastIndex].time) { return uint256(self.history[lastIndex].value); } // If the requested time is previous to the first registered value, return zero to denote missing checkpoint if (_time < self.history[0].time) { return 0; } // Execute a binary search between the checkpointed times of the history uint256 low = 0; uint256 high = lastIndex; while (high > low) { // No need for SafeMath: for this to overflow array size should be ~2^255 uint256 mid = (high + low + 1) / 2; Checkpoint storage checkpoint = self.history[mid]; uint64 midTime = checkpoint.time; if (_time > midTime) { low = mid; } else if (_time < midTime) { // No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1 high = mid - 1; } else { return uint256(checkpoint.value); } } return uint256(self.history[low].value); } } // File: @aragon/court/contracts/lib/os/Uint256Helpers.sol // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol // Adapted to use pragma ^0.5.8 and satisfy our linter rules pragma solidity ^0.5.8; library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } // File: contracts/InitializableV2.sol pragma solidity >=0.4.24 <0.7.0; /** * Wrapper around OpenZeppelin's Initializable contract. * Exposes initialized state management to ensure logic contract functions cannot be called before initialization. * This is needed because OZ's Initializable contract no longer exposes initialized state variable. * https://github.com/OpenZeppelin/openzeppelin-sdk/blob/v2.8.0/packages/lib/contracts/Initializable.sol */ contract InitializableV2 is Initializable { bool private isInitialized; string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized"; /** * @notice wrapper function around parent contract Initializable's `initializable` modifier * initializable modifier ensures this function can only be called once by each deployed child contract * sets isInitialized flag to true to which is used by _requireIsInitialized() */ function initialize() public initializer { isInitialized = true; } /** * @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure * contract is initialized before functions can be called. */ function _requireIsInitialized() internal view { require(isInitialized == true, ERROR_NOT_INITIALIZED); } /** * @notice Exposes isInitialized bool var to child contracts with read-only access */ function _isInitialized() internal view returns (bool) { return isInitialized; } } // File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: contracts/registry/Registry.sol pragma solidity ^0.5.0; /** * @title Central hub for Audius protocol. It stores all contract addresses to facilitate * external access and enable version management. */ contract Registry is InitializableV2, Ownable { using SafeMath for uint256; /** * @dev addressStorage mapping allows efficient lookup of current contract version * addressStorageHistory maintains record of all contract versions */ mapping(bytes32 => address) private addressStorage; mapping(bytes32 => address[]) private addressStorageHistory; event ContractAdded( bytes32 indexed _name, address indexed _address ); event ContractRemoved( bytes32 indexed _name, address indexed _address ); event ContractUpgraded( bytes32 indexed _name, address indexed _oldAddress, address indexed _newAddress ); function initialize() public initializer { /// @notice Ownable.initialize(address _sender) sets contract owner to _sender. Ownable.initialize(msg.sender); InitializableV2.initialize(); } // ========================================= Setters ========================================= /** * @notice addContract registers contract name to address mapping under given registry key * @param _name - registry key that will be used for lookups * @param _address - address of contract */ function addContract(bytes32 _name, address _address) external onlyOwner { _requireIsInitialized(); require( addressStorage[_name] == address(0x00), "Registry: Contract already registered with given name." ); require( _address != address(0x00), "Registry: Cannot register zero address." ); setAddress(_name, _address); emit ContractAdded(_name, _address); } /** * @notice removes contract address registered under given registry key * @param _name - registry key for lookup */ function removeContract(bytes32 _name) external onlyOwner { _requireIsInitialized(); address contractAddress = addressStorage[_name]; require( contractAddress != address(0x00), "Registry: Cannot remove - no contract registered with given _name." ); setAddress(_name, address(0x00)); emit ContractRemoved(_name, contractAddress); } /** * @notice replaces contract address registered under given key with provided address * @param _name - registry key for lookup * @param _newAddress - new contract address to register under given key */ function upgradeContract(bytes32 _name, address _newAddress) external onlyOwner { _requireIsInitialized(); address oldAddress = addressStorage[_name]; require( oldAddress != address(0x00), "Registry: Cannot upgrade - no contract registered with given _name." ); require( _newAddress != address(0x00), "Registry: Cannot upgrade - cannot register zero address." ); setAddress(_name, _newAddress); emit ContractUpgraded(_name, oldAddress, _newAddress); } // ========================================= Getters ========================================= /** * @notice returns contract address registered under given registry key * @param _name - registry key for lookup * @return contractAddr - address of contract registered under given registry key */ function getContract(bytes32 _name) external view returns (address contractAddr) { _requireIsInitialized(); return addressStorage[_name]; } /// @notice overloaded getContract to return explicit version of contract function getContract(bytes32 _name, uint256 _version) external view returns (address contractAddr) { _requireIsInitialized(); // array length for key implies version number require( _version <= addressStorageHistory[_name].length, "Registry: Index out of range _version." ); return addressStorageHistory[_name][_version.sub(1)]; } /** * @notice Returns the number of versions for a contract key * @param _name - registry key for lookup * @return number of contract versions */ function getContractVersionCount(bytes32 _name) external view returns (uint256) { _requireIsInitialized(); return addressStorageHistory[_name].length; } // ========================================= Private functions ========================================= /** * @param _key the key for the contract address * @param _value the contract address */ function setAddress(bytes32 _key, address _value) private { // main map for cheap lookup addressStorage[_key] = _value; // keep track of contract address history addressStorageHistory[_key].push(_value); } } // File: contracts/Governance.sol pragma solidity ^0.5.0; contract Governance is InitializableV2 { using SafeMath for uint256; string private constant ERROR_ONLY_GOVERNANCE = ( "Governance: Only callable by self" ); string private constant ERROR_INVALID_VOTING_PERIOD = ( "Governance: Requires non-zero _votingPeriod" ); string private constant ERROR_INVALID_REGISTRY = ( "Governance: Requires non-zero _registryAddress" ); string private constant ERROR_INVALID_VOTING_QUORUM = ( "Governance: Requires _votingQuorumPercent between 1 & 100" ); /** * @notice Address and contract instance of Audius Registry. Used to ensure this contract * can only govern contracts that are registered in the Audius Registry. */ Registry private registry; /// @notice Address of Audius staking contract, used to permission Governance method calls address private stakingAddress; /// @notice Address of Audius ServiceProvider contract, used to permission Governance method calls address private serviceProviderFactoryAddress; /// @notice Address of Audius DelegateManager contract, used to permission Governance method calls address private delegateManagerAddress; /// @notice Period in blocks for which a governance proposal is open for voting uint256 private votingPeriod; /// @notice Number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed uint256 private executionDelay; /// @notice Required minimum percentage of total stake to have voted to consider a proposal valid /// Percentaged stored as a uint256 between 0 & 100 /// Calculated as: 100 * sum of voter stakes / total staked in Staking (at proposal submission block) uint256 private votingQuorumPercent; /// @notice Max number of InProgress proposals possible at once /// @dev uint16 gives max possible value of 65,535 uint16 private maxInProgressProposals; /** * @notice Address of account that has special Governance permissions. Can veto proposals * and execute transactions directly on contracts. */ address private guardianAddress; /***** Enums *****/ /** * @notice All Proposal Outcome states. * InProgress - Proposal is active and can be voted on. * Rejected - Proposal votingPeriod has closed and vote failed to pass. Proposal will not be executed. * ApprovedExecuted - Proposal votingPeriod has closed and vote passed. Proposal was successfully executed. * QuorumNotMet - Proposal votingPeriod has closed and votingQuorumPercent was not met. Proposal will not be executed. * ApprovedExecutionFailed - Proposal vote passed, but transaction execution failed. * Evaluating - Proposal vote passed, and evaluateProposalOutcome function is currently running. * This status is transiently used inside that function to prevent re-entrancy. * Vetoed - Proposal was vetoed by Guardian. * TargetContractAddressChanged - Proposal considered invalid since target contract address changed * TargetContractCodeHashChanged - Proposal considered invalid since code has at target contract address has changed */ enum Outcome { InProgress, Rejected, ApprovedExecuted, QuorumNotMet, ApprovedExecutionFailed, Evaluating, Vetoed, TargetContractAddressChanged, TargetContractCodeHashChanged } /** * @notice All Proposal Vote states for a voter. * None - The default state, for any account that has not previously voted on this Proposal. * No - The account voted No on this Proposal. * Yes - The account voted Yes on this Proposal. * @dev Enum values map to uints, so first value in Enum always is 0. */ enum Vote {None, No, Yes} struct Proposal { uint256 proposalId; address proposer; uint256 submissionBlockNumber; bytes32 targetContractRegistryKey; address targetContractAddress; uint256 callValue; string functionSignature; bytes callData; Outcome outcome; uint256 voteMagnitudeYes; uint256 voteMagnitudeNo; uint256 numVotes; mapping(address => Vote) votes; mapping(address => uint256) voteMagnitudes; bytes32 contractHash; } /***** Proposal storage *****/ /// @notice ID of most recently created proposal. Ids are monotonically increasing and 1-indexed. uint256 lastProposalId = 0; /// @notice mapping of proposalId to Proposal struct with all proposal state mapping(uint256 => Proposal) proposals; /// @notice array of proposals with InProgress state uint256[] inProgressProposals; /***** Events *****/ event ProposalSubmitted( uint256 indexed _proposalId, address indexed _proposer, string _name, string _description ); event ProposalVoteSubmitted( uint256 indexed _proposalId, address indexed _voter, Vote indexed _vote, uint256 _voterStake ); event ProposalVoteUpdated( uint256 indexed _proposalId, address indexed _voter, Vote indexed _vote, uint256 _voterStake, Vote _previousVote ); event ProposalOutcomeEvaluated( uint256 indexed _proposalId, Outcome indexed _outcome, uint256 _voteMagnitudeYes, uint256 _voteMagnitudeNo, uint256 _numVotes ); event ProposalTransactionExecuted( uint256 indexed _proposalId, bool indexed _success, bytes _returnData ); event GuardianTransactionExecuted( address indexed _targetContractAddress, uint256 _callValue, string indexed _functionSignature, bytes indexed _callData, bytes _returnData ); event ProposalVetoed(uint256 indexed _proposalId); event RegistryAddressUpdated(address indexed _newRegistryAddress); event GuardianshipTransferred(address indexed _newGuardianAddress); event VotingPeriodUpdated(uint256 indexed _newVotingPeriod); event ExecutionDelayUpdated(uint256 indexed _newExecutionDelay); event VotingQuorumPercentUpdated(uint256 indexed _newVotingQuorumPercent); event MaxInProgressProposalsUpdated(uint256 indexed _newMaxInProgressProposals); /** * @notice Initialize the Governance contract * @dev _votingPeriod <= DelegateManager.undelegateLockupDuration * @dev stakingAddress must be initialized separately after Staking contract is deployed * @param _registryAddress - address of the registry proxy contract * @param _votingPeriod - period in blocks for which a governance proposal is open for voting * @param _executionDelay - number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed * @param _votingQuorumPercent - required minimum percentage of total stake to have voted to consider a proposal valid * @param _maxInProgressProposals - max number of InProgress proposals possible at once * @param _guardianAddress - address of account that has special Governance permissions */ function initialize( address _registryAddress, uint256 _votingPeriod, uint256 _executionDelay, uint256 _votingQuorumPercent, uint16 _maxInProgressProposals, address _guardianAddress ) public initializer { require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY); registry = Registry(_registryAddress); require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD); votingPeriod = _votingPeriod; // executionDelay does not have to be non-zero executionDelay = _executionDelay; require( _maxInProgressProposals > 0, "Governance: Requires non-zero _maxInProgressProposals" ); maxInProgressProposals = _maxInProgressProposals; require( _votingQuorumPercent > 0 && _votingQuorumPercent <= 100, ERROR_INVALID_VOTING_QUORUM ); votingQuorumPercent = _votingQuorumPercent; require( _guardianAddress != address(0x00), "Governance: Requires non-zero _guardianAddress" ); guardianAddress = _guardianAddress; //Guardian address becomes the only party InitializableV2.initialize(); } // ========================================= Governance Actions ========================================= /** * @notice Submit a proposal for vote. Only callable by addresses with non-zero total active stake. * total active stake = total active deployer stake + total active delegator stake * * @dev _name and _description length is not enforced since they aren't stored on-chain and only event emitted * * @param _targetContractRegistryKey - Registry key for the contract concerning this proposal * @param _callValue - amount of wei to pass with function call if a token transfer is involved * @param _functionSignature - function signature of the function to be executed if proposal is successful * @param _callData - encoded value(s) to call function with if proposal is successful * @param _name - Text name of proposal to be emitted in event * @param _description - Text description of proposal to be emitted in event * * @return - ID of new proposal */ function submitProposal( bytes32 _targetContractRegistryKey, uint256 _callValue, string calldata _functionSignature, bytes calldata _callData, string calldata _name, string calldata _description ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireDelegateManagerAddressIsSet(); address proposer = msg.sender; // Require all InProgress proposals that can be evaluated have been evaluated before new proposal submission require( this.inProgressProposalsAreUpToDate(), "Governance: Cannot submit new proposal until all evaluatable InProgress proposals are evaluated." ); // Require new proposal submission would not push number of InProgress proposals over max number require( inProgressProposals.length < maxInProgressProposals, "Governance: Number of InProgress proposals already at max. Please evaluate if possible, or wait for current proposals' votingPeriods to expire." ); // Require proposer has non-zero total active stake or is guardian address require( _calculateAddressActiveStake(proposer) > 0 || proposer == guardianAddress, "Governance: Proposer must be address with non-zero total active stake or be guardianAddress." ); // Require _targetContractRegistryKey points to a valid registered contract address targetContractAddress = registry.getContract(_targetContractRegistryKey); require( targetContractAddress != address(0x00), "Governance: _targetContractRegistryKey must point to valid registered contract" ); // Signature cannot be empty require( bytes(_functionSignature).length != 0, "Governance: _functionSignature cannot be empty." ); // Require non-zero description length require(bytes(_description).length > 0, "Governance: _description length must be > 0"); // Require non-zero name length require(bytes(_name).length > 0, "Governance: _name length must be > 0"); // set proposalId uint256 newProposalId = lastProposalId.add(1); // Store new Proposal obj in proposals mapping proposals[newProposalId] = Proposal({ proposalId: newProposalId, proposer: proposer, submissionBlockNumber: block.number, targetContractRegistryKey: _targetContractRegistryKey, targetContractAddress: targetContractAddress, callValue: _callValue, functionSignature: _functionSignature, callData: _callData, outcome: Outcome.InProgress, voteMagnitudeYes: 0, voteMagnitudeNo: 0, numVotes: 0, contractHash: _getCodeHash(targetContractAddress) /* votes: mappings are auto-initialized to default state */ /* voteMagnitudes: mappings are auto-initialized to default state */ }); // Append new proposalId to inProgressProposals array inProgressProposals.push(newProposalId); emit ProposalSubmitted( newProposalId, proposer, _name, _description ); lastProposalId = newProposalId; return newProposalId; } /** * @notice Vote on an active Proposal. Only callable by addresses with non-zero active stake. * @param _proposalId - id of the proposal this vote is for * @param _vote - can be either {Yes, No} from Vote enum. No other values allowed */ function submitVote(uint256 _proposalId, Vote _vote) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireDelegateManagerAddressIsSet(); _requireValidProposalId(_proposalId); address voter = msg.sender; // Require proposal votingPeriod is still active uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber; uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod); require( block.number > submissionBlockNumber && block.number <= endBlockNumber, "Governance: Proposal votingPeriod has ended" ); // Require voter has non-zero total active stake uint256 voterActiveStake = _calculateAddressActiveStake(voter); require( voterActiveStake > 0, "Governance: Voter must be address with non-zero total active stake." ); // Require previous vote is None require( proposals[_proposalId].votes[voter] == Vote.None, "Governance: To update previous vote, call updateVote()" ); // Require vote is either Yes or No require( _vote == Vote.Yes || _vote == Vote.No, "Governance: Can only submit a Yes or No vote" ); // Record vote proposals[_proposalId].votes[voter] = _vote; // Record voteMagnitude for voter proposals[_proposalId].voteMagnitudes[voter] = voterActiveStake; // Update proposal cumulative vote magnitudes if (_vote == Vote.Yes) { _increaseVoteMagnitudeYes(_proposalId, voterActiveStake); } else { _increaseVoteMagnitudeNo(_proposalId, voterActiveStake); } // Increment proposal numVotes proposals[_proposalId].numVotes = proposals[_proposalId].numVotes.add(1); emit ProposalVoteSubmitted( _proposalId, voter, _vote, voterActiveStake ); } /** * @notice Update previous vote on an active Proposal. Only callable by addresses with non-zero active stake. * @param _proposalId - id of the proposal this vote is for * @param _vote - can be either {Yes, No} from Vote enum. No other values allowed */ function updateVote(uint256 _proposalId, Vote _vote) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireDelegateManagerAddressIsSet(); _requireValidProposalId(_proposalId); address voter = msg.sender; // Require proposal votingPeriod is still active uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber; uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod); require( block.number > submissionBlockNumber && block.number <= endBlockNumber, "Governance: Proposal votingPeriod has ended" ); // Retrieve previous vote Vote previousVote = proposals[_proposalId].votes[voter]; // Require previous vote is not None require( previousVote != Vote.None, "Governance: To submit new vote, call submitVote()" ); // Require vote is either Yes or No require( _vote == Vote.Yes || _vote == Vote.No, "Governance: Can only submit a Yes or No vote" ); // Record updated vote proposals[_proposalId].votes[voter] = _vote; // Update vote magnitudes, using vote magnitude from when previous vote was submitted uint256 voteMagnitude = proposals[_proposalId].voteMagnitudes[voter]; if (previousVote == Vote.Yes && _vote == Vote.No) { _decreaseVoteMagnitudeYes(_proposalId, voteMagnitude); _increaseVoteMagnitudeNo(_proposalId, voteMagnitude); } else if (previousVote == Vote.No && _vote == Vote.Yes) { _decreaseVoteMagnitudeNo(_proposalId, voteMagnitude); _increaseVoteMagnitudeYes(_proposalId, voteMagnitude); } // If _vote == previousVote, no changes needed to vote magnitudes. // Do not update numVotes emit ProposalVoteUpdated( _proposalId, voter, _vote, voteMagnitude, previousVote ); } /** * @notice Once the voting period + executionDelay for a proposal has ended, evaluate the outcome and * execute the proposal if voting quorum met & vote passes. * To pass, stake-weighted vote must be > 50% Yes. * @dev Requires that caller is an active staker at the time the proposal is created * @param _proposalId - id of the proposal * @return Outcome of proposal evaluation */ function evaluateProposalOutcome(uint256 _proposalId) external returns (Outcome) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireDelegateManagerAddressIsSet(); _requireValidProposalId(_proposalId); // Require proposal has not already been evaluated. require( proposals[_proposalId].outcome == Outcome.InProgress, "Governance: Can only evaluate InProgress proposal." ); // Re-entrancy should not be possible here since this switches the status of the // proposal to 'Evaluating' so it should fail the status is 'InProgress' check proposals[_proposalId].outcome = Outcome.Evaluating; // Require proposal votingPeriod + executionDelay have ended. uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber; uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod).add(executionDelay); require( block.number > endBlockNumber, "Governance: Proposal votingPeriod & executionDelay must end before evaluation." ); address targetContractAddress = registry.getContract( proposals[_proposalId].targetContractRegistryKey ); Outcome outcome; // target contract address changed -> close proposal without execution. if (targetContractAddress != proposals[_proposalId].targetContractAddress) { outcome = Outcome.TargetContractAddressChanged; } // target contract code hash changed -> close proposal without execution. else if (_getCodeHash(targetContractAddress) != proposals[_proposalId].contractHash) { outcome = Outcome.TargetContractCodeHashChanged; } // voting quorum not met -> close proposal without execution. else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) { outcome = Outcome.QuorumNotMet; } // votingQuorumPercent met & vote passed -> execute proposed transaction & close proposal. else if ( proposals[_proposalId].voteMagnitudeYes > proposals[_proposalId].voteMagnitudeNo ) { (bool success, bytes memory returnData) = _executeTransaction( targetContractAddress, proposals[_proposalId].callValue, proposals[_proposalId].functionSignature, proposals[_proposalId].callData ); emit ProposalTransactionExecuted( _proposalId, success, returnData ); // Proposal outcome depends on success of transaction execution. if (success) { outcome = Outcome.ApprovedExecuted; } else { outcome = Outcome.ApprovedExecutionFailed; } } // votingQuorumPercent met & vote did not pass -> close proposal without transaction execution. else { outcome = Outcome.Rejected; } // This records the final outcome in the proposals mapping proposals[_proposalId].outcome = outcome; // Remove from inProgressProposals array _removeFromInProgressProposals(_proposalId); emit ProposalOutcomeEvaluated( _proposalId, outcome, proposals[_proposalId].voteMagnitudeYes, proposals[_proposalId].voteMagnitudeNo, proposals[_proposalId].numVotes ); return outcome; } /** * @notice Action limited to the guardian address that can veto a proposal * @param _proposalId - id of the proposal */ function vetoProposal(uint256 _proposalId) external { _requireIsInitialized(); _requireValidProposalId(_proposalId); require( msg.sender == guardianAddress, "Governance: Only guardian can veto proposals." ); require( proposals[_proposalId].outcome == Outcome.InProgress, "Governance: Cannot veto inactive proposal." ); proposals[_proposalId].outcome = Outcome.Vetoed; // Remove from inProgressProposals array _removeFromInProgressProposals(_proposalId); emit ProposalVetoed(_proposalId); } // ========================================= Config Setters ========================================= /** * @notice Set the Staking address * @dev Only callable by self via _executeTransaction * @param _stakingAddress - address for new Staking contract */ function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require(_stakingAddress != address(0x00), "Governance: Requires non-zero _stakingAddress"); stakingAddress = _stakingAddress; } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by self via _executeTransaction * @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require( _serviceProviderFactoryAddress != address(0x00), "Governance: Requires non-zero _serviceProviderFactoryAddress" ); serviceProviderFactoryAddress = _serviceProviderFactoryAddress; } /** * @notice Set the DelegateManager address * @dev Only callable by self via _executeTransaction * @param _delegateManagerAddress - address for new DelegateManager contract */ function setDelegateManagerAddress(address _delegateManagerAddress) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require( _delegateManagerAddress != address(0x00), "Governance: Requires non-zero _delegateManagerAddress" ); delegateManagerAddress = _delegateManagerAddress; } /** * @notice Set the voting period for a Governance proposal * @dev Only callable by self via _executeTransaction * @param _votingPeriod - new voting period */ function setVotingPeriod(uint256 _votingPeriod) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD); votingPeriod = _votingPeriod; emit VotingPeriodUpdated(_votingPeriod); } /** * @notice Set the voting quorum percentage for a Governance proposal * @dev Only callable by self via _executeTransaction * @param _votingQuorumPercent - new voting period */ function setVotingQuorumPercent(uint256 _votingQuorumPercent) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require( _votingQuorumPercent > 0 && _votingQuorumPercent <= 100, ERROR_INVALID_VOTING_QUORUM ); votingQuorumPercent = _votingQuorumPercent; emit VotingQuorumPercentUpdated(_votingQuorumPercent); } /** * @notice Set the Registry address * @dev Only callable by self via _executeTransaction * @param _registryAddress - address for new Registry contract */ function setRegistryAddress(address _registryAddress) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY); registry = Registry(_registryAddress); emit RegistryAddressUpdated(_registryAddress); } /** * @notice Set the max number of concurrent InProgress proposals * @dev Only callable by self via _executeTransaction * @param _newMaxInProgressProposals - new value for maxInProgressProposals */ function setMaxInProgressProposals(uint16 _newMaxInProgressProposals) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require( _newMaxInProgressProposals > 0, "Governance: Requires non-zero _newMaxInProgressProposals" ); maxInProgressProposals = _newMaxInProgressProposals; emit MaxInProgressProposalsUpdated(_newMaxInProgressProposals); } /** * @notice Set the execution delay for a proposal * @dev Only callable by self via _executeTransaction * @param _newExecutionDelay - new value for executionDelay */ function setExecutionDelay(uint256 _newExecutionDelay) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); // executionDelay does not have to be non-zero executionDelay = _newExecutionDelay; emit ExecutionDelayUpdated(_newExecutionDelay); } // ========================================= Guardian Actions ========================================= /** * @notice Allows the guardianAddress to execute protocol actions * @param _targetContractRegistryKey - key in registry of target contract * @param _callValue - amount of wei if a token transfer is involved * @param _functionSignature - function signature of the function to be executed if proposal is successful * @param _callData - encoded value(s) to call function with if proposal is successful */ function guardianExecuteTransaction( bytes32 _targetContractRegistryKey, uint256 _callValue, string calldata _functionSignature, bytes calldata _callData ) external { _requireIsInitialized(); require( msg.sender == guardianAddress, "Governance: Only guardian." ); // _targetContractRegistryKey must point to a valid registered contract address targetContractAddress = registry.getContract(_targetContractRegistryKey); require( targetContractAddress != address(0x00), "Governance: _targetContractRegistryKey must point to valid registered contract" ); // Signature cannot be empty require( bytes(_functionSignature).length != 0, "Governance: _functionSignature cannot be empty." ); (bool success, bytes memory returnData) = _executeTransaction( targetContractAddress, _callValue, _functionSignature, _callData ); require(success, "Governance: Transaction failed."); emit GuardianTransactionExecuted( targetContractAddress, _callValue, _functionSignature, _callData, returnData ); } /** * @notice Change the guardian address * @dev Only callable by current guardian * @param _newGuardianAddress - new guardian address */ function transferGuardianship(address _newGuardianAddress) external { _requireIsInitialized(); require( msg.sender == guardianAddress, "Governance: Only guardian." ); guardianAddress = _newGuardianAddress; emit GuardianshipTransferred(_newGuardianAddress); } // ========================================= Getter Functions ========================================= /** * @notice Get proposal information by proposal Id * @param _proposalId - id of proposal */ function getProposalById(uint256 _proposalId) external view returns ( uint256 proposalId, address proposer, uint256 submissionBlockNumber, bytes32 targetContractRegistryKey, address targetContractAddress, uint256 callValue, string memory functionSignature, bytes memory callData, Outcome outcome, uint256 voteMagnitudeYes, uint256 voteMagnitudeNo, uint256 numVotes ) { _requireIsInitialized(); _requireValidProposalId(_proposalId); Proposal memory proposal = proposals[_proposalId]; return ( proposal.proposalId, proposal.proposer, proposal.submissionBlockNumber, proposal.targetContractRegistryKey, proposal.targetContractAddress, proposal.callValue, proposal.functionSignature, proposal.callData, proposal.outcome, proposal.voteMagnitudeYes, proposal.voteMagnitudeNo, proposal.numVotes /** @notice - votes mapping cannot be returned by external function */ /** @notice - voteMagnitudes mapping cannot be returned by external function */ /** @notice - returning contractHash leads to stack too deep compiler error, see getProposalTargetContractHash() */ ); } /** * @notice Get proposal target contract hash by proposalId * @dev This is a separate function because the getProposalById returns too many variables already and by adding more, you get the error `InternalCompilerError: Stack too deep, try using fewer variables` * @param _proposalId - id of proposal */ function getProposalTargetContractHash(uint256 _proposalId) external view returns (bytes32) { _requireIsInitialized(); _requireValidProposalId(_proposalId); return (proposals[_proposalId].contractHash); } /** * @notice Get vote direction and vote magnitude for a given proposal and voter * @param _proposalId - id of the proposal * @param _voter - address of the voter we want to check * @return returns vote direction and magnitude if valid vote, else default values */ function getVoteInfoByProposalAndVoter(uint256 _proposalId, address _voter) external view returns (Vote vote, uint256 voteMagnitude) { _requireIsInitialized(); _requireValidProposalId(_proposalId); return ( proposals[_proposalId].votes[_voter], proposals[_proposalId].voteMagnitudes[_voter] ); } /// @notice Get the contract Guardian address function getGuardianAddress() external view returns (address) { _requireIsInitialized(); return guardianAddress; } /// @notice Get the Staking address function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the DelegateManager address function getDelegateManagerAddress() external view returns (address) { _requireIsInitialized(); return delegateManagerAddress; } /// @notice Get the contract voting period function getVotingPeriod() external view returns (uint256) { _requireIsInitialized(); return votingPeriod; } /// @notice Get the contract voting quorum percent function getVotingQuorumPercent() external view returns (uint256) { _requireIsInitialized(); return votingQuorumPercent; } /// @notice Get the registry address function getRegistryAddress() external view returns (address) { _requireIsInitialized(); return address(registry); } /// @notice Used to check if is governance contract before setting governance address in other contracts function isGovernanceAddress() external pure returns (bool) { return true; } /// @notice Get the max number of concurrent InProgress proposals function getMaxInProgressProposals() external view returns (uint16) { _requireIsInitialized(); return maxInProgressProposals; } /// @notice Get the proposal execution delay function getExecutionDelay() external view returns (uint256) { _requireIsInitialized(); return executionDelay; } /// @notice Get the array of all InProgress proposal Ids function getInProgressProposals() external view returns (uint256[] memory) { _requireIsInitialized(); return inProgressProposals; } /** * @notice Returns false if any proposals in inProgressProposals array are evaluatable * Evaluatable = proposals with closed votingPeriod * @dev Is public since its called internally in `submitProposal()` as well as externally in UI */ function inProgressProposalsAreUpToDate() external view returns (bool) { _requireIsInitialized(); // compare current block number against endBlockNumber of each proposal for (uint256 i = 0; i < inProgressProposals.length; i++) { if ( block.number > (proposals[inProgressProposals[i]].submissionBlockNumber).add(votingPeriod).add(executionDelay) ) { return false; } } return true; } // ========================================= Internal Functions ========================================= /** * @notice Execute a transaction attached to a governance proposal * @dev We are aware of both potential re-entrancy issues and the risks associated with low-level solidity * function calls here, but have chosen to keep this code with those issues in mind. All governance * proposals go through a voting process, and all will be reviewed carefully to ensure that they * adhere to the expected behaviors of this call - but adding restrictions here would limit the ability * of the governance system to do required work in a generic way. * @param _targetContractAddress - address of registry proxy contract to execute transaction on * @param _callValue - amount of wei if a token transfer is involved * @param _functionSignature - function signature of the function to be executed if proposal is successful * @param _callData - encoded value(s) to call function with if proposal is successful */ function _executeTransaction( address _targetContractAddress, uint256 _callValue, string memory _functionSignature, bytes memory _callData ) internal returns (bool success, bytes memory returnData) { bytes memory encodedCallData = abi.encodePacked( bytes4(keccak256(bytes(_functionSignature))), _callData ); (success, returnData) = ( // solium-disable-next-line security/no-call-value _targetContractAddress.call.value(_callValue)(encodedCallData) ); return (success, returnData); } function _increaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal { proposals[_proposalId].voteMagnitudeYes = ( proposals[_proposalId].voteMagnitudeYes.add(_voterStake) ); } function _increaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal { proposals[_proposalId].voteMagnitudeNo = ( proposals[_proposalId].voteMagnitudeNo.add(_voterStake) ); } function _decreaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal { proposals[_proposalId].voteMagnitudeYes = ( proposals[_proposalId].voteMagnitudeYes.sub(_voterStake) ); } function _decreaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal { proposals[_proposalId].voteMagnitudeNo = ( proposals[_proposalId].voteMagnitudeNo.sub(_voterStake) ); } /** * @dev Can make O(1) by storing index pointer in proposals mapping. * Requires inProgressProposals to be 1-indexed, since all proposals that are not present * will have pointer set to 0. */ function _removeFromInProgressProposals(uint256 _proposalId) internal { uint256 index = 0; for (uint256 i = 0; i < inProgressProposals.length; i++) { if (inProgressProposals[i] == _proposalId) { index = i; break; } } // Swap proposalId to end of array + pop (deletes last elem + decrements array length) inProgressProposals[index] = inProgressProposals[inProgressProposals.length - 1]; inProgressProposals.pop(); } /** * @notice Returns true if voting quorum percentage met for proposal, else false. * @dev Quorum is met if total voteMagnitude * 100 / total active stake in Staking * @dev Eventual multiplication overflow: * (proposal.voteMagnitudeYes + proposal.voteMagnitudeNo), with 100% staking participation, * can sum to at most the entire token supply of 10^27 * With 7% annual token supply inflation, multiplication can overflow ~1635 years at the earliest: * log(2^256/(10^27*100))/log(1.07) ~= 1635 * * @dev Note that quorum is evaluated based on total staked at proposal submission * not total staked at proposal evaluation, this is expected behavior */ function _quorumMet(Proposal memory proposal, Staking stakingContract) internal view returns (bool) { uint256 participation = ( (proposal.voteMagnitudeYes + proposal.voteMagnitudeNo) .mul(100) .div(stakingContract.totalStakedAt(proposal.submissionBlockNumber)) ); return participation >= votingQuorumPercent; } // ========================================= Private Functions ========================================= function _requireStakingAddressIsSet() private view { require( stakingAddress != address(0x00), "Governance: stakingAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "Governance: serviceProviderFactoryAddress is not set" ); } function _requireDelegateManagerAddressIsSet() private view { require( delegateManagerAddress != address(0x00), "Governance: delegateManagerAddress is not set" ); } function _requireValidProposalId(uint256 _proposalId) private view { require( _proposalId <= lastProposalId && _proposalId > 0, "Governance: Must provide valid non-zero _proposalId" ); } /** * Calculates and returns active stake for address * * Active stake = (active deployer stake + active delegator stake) * active deployer stake = (direct deployer stake - locked deployer stake) * locked deployer stake = amount of pending decreaseStakeRequest for address * active delegator stake = (total delegator stake - locked delegator stake) * locked delegator stake = amount of pending undelegateRequest for address */ function _calculateAddressActiveStake(address _address) private view returns (uint256) { ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); DelegateManagerV2 delegateManager = DelegateManagerV2(delegateManagerAddress); // Amount directly staked by address, if any, in ServiceProviderFactory (uint256 directDeployerStake,,,,,) = spFactory.getServiceProviderDetails(_address); // Amount of pending decreasedStakeRequest for address, if any, in ServiceProviderFactory (uint256 lockedDeployerStake,) = spFactory.getPendingDecreaseStakeRequest(_address); // active deployer stake = (direct deployer stake - locked deployer stake) uint256 activeDeployerStake = directDeployerStake.sub(lockedDeployerStake); // Total amount delegated by address, if any, in DelegateManager uint256 totalDelegatorStake = delegateManager.getTotalDelegatorStake(_address); // Amount of pending undelegateRequest for address, if any, in DelegateManager (,uint256 lockedDelegatorStake, ) = delegateManager.getPendingUndelegateRequest(_address); // active delegator stake = (total delegator stake - locked delegator stake) uint256 activeDelegatorStake = totalDelegatorStake.sub(lockedDelegatorStake); // activeStake = (activeDeployerStake + activeDelegatorStake) uint256 activeStake = activeDeployerStake.add(activeDelegatorStake); return activeStake; } // solium-disable security/no-inline-assembly /** * @notice Helper function to generate the code hash for a contract address * @return contract code hash */ function _getCodeHash(address _contract) private view returns (bytes32) { bytes32 contractHash; assembly { contractHash := extcodehash(_contract) } return contractHash; } } // File: contracts/Staking.sol pragma solidity ^0.5.0; contract Staking is InitializableV2 { using SafeMath for uint256; using Uint256Helpers for uint256; using Checkpointing for Checkpointing.History; using SafeERC20 for ERC20; string private constant ERROR_TOKEN_NOT_CONTRACT = "Staking: Staking token is not a contract"; string private constant ERROR_AMOUNT_ZERO = "Staking: Zero amount not allowed"; string private constant ERROR_ONLY_GOVERNANCE = "Staking: Only governance"; string private constant ERROR_ONLY_DELEGATE_MANAGER = ( "Staking: Only callable from DelegateManager" ); string private constant ERROR_ONLY_SERVICE_PROVIDER_FACTORY = ( "Staking: Only callable from ServiceProviderFactory" ); address private governanceAddress; address private claimsManagerAddress; address private delegateManagerAddress; address private serviceProviderFactoryAddress; /// @dev stores the history of staking and claims for a given address struct Account { Checkpointing.History stakedHistory; Checkpointing.History claimHistory; } /// @dev ERC-20 token that will be used to stake with ERC20 internal stakingToken; /// @dev maps addresses to staking and claims history mapping (address => Account) internal accounts; /// @dev total staked tokens at a given block Checkpointing.History internal totalStakedHistory; event Staked(address indexed user, uint256 amount, uint256 total); event Unstaked(address indexed user, uint256 amount, uint256 total); event Slashed(address indexed user, uint256 amount, uint256 total); /** * @notice Function to initialize the contract * @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed * @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed * @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed * @param _tokenAddress - address of ERC20 token that will be staked * @param _governanceAddress - address for Governance proxy contract */ function initialize( address _tokenAddress, address _governanceAddress ) public initializer { require(Address.isContract(_tokenAddress), ERROR_TOKEN_NOT_CONTRACT); stakingToken = ERC20(_tokenAddress); _updateGovernanceAddress(_governanceAddress); InitializableV2.initialize(); } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); } /** * @notice Set the ClaimsManaager address * @dev Only callable by Governance address * @param _claimsManager - address for new ClaimsManaager contract */ function setClaimsManagerAddress(address _claimsManager) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); claimsManagerAddress = _claimsManager; } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by Governance address * @param _spFactory - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _spFactory) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceProviderFactoryAddress = _spFactory; } /** * @notice Set the DelegateManager address * @dev Only callable by Governance address * @param _delegateManager - address for new DelegateManager contract */ function setDelegateManagerAddress(address _delegateManager) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); delegateManagerAddress = _delegateManager; } /* External functions */ /** * @notice Funds `_amount` of tokens from ClaimsManager to target account * @param _amount - amount of rewards to add to stake * @param _stakerAccount - address of staker */ function stakeRewards(uint256 _amount, address _stakerAccount) external { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( msg.sender == claimsManagerAddress, "Staking: Only callable from ClaimsManager" ); _stakeFor(_stakerAccount, msg.sender, _amount); this.updateClaimHistory(_amount, _stakerAccount); } /** * @notice Update claim history by adding an event to the claim history * @param _amount - amount to add to claim history * @param _stakerAccount - address of staker */ function updateClaimHistory(uint256 _amount, address _stakerAccount) external { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( msg.sender == claimsManagerAddress || msg.sender == address(this), "Staking: Only callable from ClaimsManager or Staking.sol" ); // Update claim history even if no value claimed accounts[_stakerAccount].claimHistory.add(block.number.toUint64(), _amount); } /** * @notice Slashes `_amount` tokens from _slashAddress * @dev Callable from DelegateManager * @param _amount - Number of tokens slashed * @param _slashAddress - Address being slashed */ function slash( uint256 _amount, address _slashAddress ) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == delegateManagerAddress, ERROR_ONLY_DELEGATE_MANAGER ); // Burn slashed tokens from account _burnFor(_slashAddress, _amount); emit Slashed( _slashAddress, _amount, totalStakedFor(_slashAddress) ); } /** * @notice Stakes `_amount` tokens, transferring them from _accountAddress, and assigns them to `_accountAddress` * @param _accountAddress - The final staker of the tokens * @param _amount - Number of tokens staked */ function stakeFor( address _accountAddress, uint256 _amount ) external { _requireIsInitialized(); _requireServiceProviderFactoryAddressIsSet(); require( msg.sender == serviceProviderFactoryAddress, ERROR_ONLY_SERVICE_PROVIDER_FACTORY ); _stakeFor( _accountAddress, _accountAddress, _amount ); } /** * @notice Unstakes `_amount` tokens, returning them to the desired account. * @param _accountAddress - Account unstaked for, and token recipient * @param _amount - Number of tokens staked */ function unstakeFor( address _accountAddress, uint256 _amount ) external { _requireIsInitialized(); _requireServiceProviderFactoryAddressIsSet(); require( msg.sender == serviceProviderFactoryAddress, ERROR_ONLY_SERVICE_PROVIDER_FACTORY ); _unstakeFor( _accountAddress, _accountAddress, _amount ); } /** * @notice Stakes `_amount` tokens, transferring them from `_delegatorAddress` to `_accountAddress`, only callable by DelegateManager * @param _accountAddress - The final staker of the tokens * @param _delegatorAddress - Address from which to transfer tokens * @param _amount - Number of tokens staked */ function delegateStakeFor( address _accountAddress, address _delegatorAddress, uint256 _amount ) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == delegateManagerAddress, ERROR_ONLY_DELEGATE_MANAGER ); _stakeFor( _accountAddress, _delegatorAddress, _amount); } /** * @notice Unstakes '_amount` tokens, transferring them from `_accountAddress` to `_delegatorAddress`, only callable by DelegateManager * @param _accountAddress - The staker of the tokens * @param _delegatorAddress - Address from which to transfer tokens * @param _amount - Number of tokens unstaked */ function undelegateStakeFor( address _accountAddress, address _delegatorAddress, uint256 _amount ) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == delegateManagerAddress, ERROR_ONLY_DELEGATE_MANAGER ); _unstakeFor( _accountAddress, _delegatorAddress, _amount); } /** * @notice Get the token used by the contract for staking and locking * @return The token used by the contract for staking and locking */ function token() external view returns (address) { _requireIsInitialized(); return address(stakingToken); } /** * @notice Check whether it supports history of stakes * @return Always true */ function supportsHistory() external view returns (bool) { _requireIsInitialized(); return true; } /** * @notice Get last time `_accountAddress` modified its staked balance * @param _accountAddress - Account requesting for * @return Last block number when account's balance was modified */ function lastStakedFor(address _accountAddress) external view returns (uint256) { _requireIsInitialized(); uint256 length = accounts[_accountAddress].stakedHistory.history.length; if (length > 0) { return uint256(accounts[_accountAddress].stakedHistory.history[length - 1].time); } return 0; } /** * @notice Get last time `_accountAddress` claimed a staking reward * @param _accountAddress - Account requesting for * @return Last block number when claim requested */ function lastClaimedFor(address _accountAddress) external view returns (uint256) { _requireIsInitialized(); uint256 length = accounts[_accountAddress].claimHistory.history.length; if (length > 0) { return uint256(accounts[_accountAddress].claimHistory.history[length - 1].time); } return 0; } /** * @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber` * @param _accountAddress - Account requesting for * @param _blockNumber - Block number at which we are requesting * @return The amount of tokens staked by the account at the given block number */ function totalStakedForAt( address _accountAddress, uint256 _blockNumber ) external view returns (uint256) { _requireIsInitialized(); return accounts[_accountAddress].stakedHistory.get(_blockNumber.toUint64()); } /** * @notice Get the total amount of tokens staked by all users at block number `_blockNumber` * @param _blockNumber - Block number at which we are requesting * @return The amount of tokens staked at the given block number */ function totalStakedAt(uint256 _blockNumber) external view returns (uint256) { _requireIsInitialized(); return totalStakedHistory.get(_blockNumber.toUint64()); } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the ClaimsManager address function getClaimsManagerAddress() external view returns (address) { _requireIsInitialized(); return claimsManagerAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the DelegateManager address function getDelegateManagerAddress() external view returns (address) { _requireIsInitialized(); return delegateManagerAddress; } /** * @notice Helper function wrapped around totalStakedFor. Checks whether _accountAddress is currently a valid staker with a non-zero stake * @param _accountAddress - Account requesting for * @return Boolean indicating whether account is a staker */ function isStaker(address _accountAddress) external view returns (bool) { _requireIsInitialized(); return totalStakedFor(_accountAddress) > 0; } /* Public functions */ /** * @notice Get the amount of tokens staked by `_accountAddress` * @param _accountAddress - The owner of the tokens * @return The amount of tokens staked by the given account */ function totalStakedFor(address _accountAddress) public view returns (uint256) { _requireIsInitialized(); // we assume it's not possible to stake in the future return accounts[_accountAddress].stakedHistory.getLast(); } /** * @notice Get the total amount of tokens staked by all users * @return The total amount of tokens staked by all users */ function totalStaked() public view returns (uint256) { _requireIsInitialized(); // we assume it's not possible to stake in the future return totalStakedHistory.getLast(); } // ========================================= Internal Functions ========================================= /** * @notice Adds stake from a transfer account to the stake account * @param _stakeAccount - Account that funds will be staked for * @param _transferAccount - Account that funds will be transferred from * @param _amount - amount to stake */ function _stakeFor( address _stakeAccount, address _transferAccount, uint256 _amount ) internal { // staking 0 tokens is invalid require(_amount > 0, ERROR_AMOUNT_ZERO); // Checkpoint updated staking balance _modifyStakeBalance(_stakeAccount, _amount, true); // checkpoint total supply _modifyTotalStaked(_amount, true); // pull tokens into Staking contract stakingToken.safeTransferFrom(_transferAccount, address(this), _amount); emit Staked( _stakeAccount, _amount, totalStakedFor(_stakeAccount)); } /** * @notice Unstakes tokens from a stake account to a transfer account * @param _stakeAccount - Account that staked funds will be transferred from * @param _transferAccount - Account that funds will be transferred to * @param _amount - amount to unstake */ function _unstakeFor( address _stakeAccount, address _transferAccount, uint256 _amount ) internal { require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(_stakeAccount, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); // transfer tokens stakingToken.safeTransfer(_transferAccount, _amount); emit Unstaked( _stakeAccount, _amount, totalStakedFor(_stakeAccount) ); } /** * @notice Burn tokens for a given staker * @dev Called when slash occurs * @param _stakeAccount - Account for which funds will be burned * @param _amount - amount to burn */ function _burnFor(address _stakeAccount, uint256 _amount) internal { // burning zero tokens is not allowed require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(_stakeAccount, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); // burn ERC20Burnable(address(stakingToken)).burn(_amount); /** No event emitted since token.burn() call already emits a Transfer event */ } /** * @notice Increase or decrease the staked balance for an account * @param _accountAddress - Account to modify * @param _by - amount to modify * @param _increase - true if increase in stake, false if decrease */ function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal { uint256 currentInternalStake = accounts[_accountAddress].stakedHistory.getLast(); uint256 newStake; if (_increase) { newStake = currentInternalStake.add(_by); } else { require( currentInternalStake >= _by, "Staking: Cannot decrease greater than current balance"); newStake = currentInternalStake.sub(_by); } // add new value to account history accounts[_accountAddress].stakedHistory.add(block.number.toUint64(), newStake); } /** * @notice Increase or decrease the staked balance across all accounts * @param _by - amount to modify * @param _increase - true if increase in stake, false if decrease */ function _modifyTotalStaked(uint256 _by, bool _increase) internal { uint256 currentStake = totalStaked(); uint256 newStake; if (_increase) { newStake = currentStake.add(_by); } else { newStake = currentStake.sub(_by); } // add new value to total history totalStakedHistory.add(block.number.toUint64(), newStake); } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "Staking: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } // ========================================= Private Functions ========================================= function _requireClaimsManagerAddressIsSet() private view { require(claimsManagerAddress != address(0x00), "Staking: claimsManagerAddress is not set"); } function _requireDelegateManagerAddressIsSet() private view { require( delegateManagerAddress != address(0x00), "Staking: delegateManagerAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "Staking: serviceProviderFactoryAddress is not set" ); } } // File: contracts/ServiceTypeManager.sol pragma solidity ^0.5.0; contract ServiceTypeManager is InitializableV2 { address governanceAddress; string private constant ERROR_ONLY_GOVERNANCE = ( "ServiceTypeManager: Only callable by Governance contract" ); /** * @dev - mapping of serviceType - serviceTypeVersion * Example - "discovery-provider" - ["0.0.1", "0.0.2", ..., "currentVersion"] */ mapping(bytes32 => bytes32[]) private serviceTypeVersions; /** * @dev - mapping of serviceType - < serviceTypeVersion, isValid > * Example - "discovery-provider" - <"0.0.1", true> */ mapping(bytes32 => mapping(bytes32 => bool)) private serviceTypeVersionInfo; /// @dev List of valid service types bytes32[] private validServiceTypes; /// @dev Struct representing service type info struct ServiceTypeInfo { bool isValid; uint256 minStake; uint256 maxStake; } /// @dev mapping of service type info mapping(bytes32 => ServiceTypeInfo) private serviceTypeInfo; event SetServiceVersion( bytes32 indexed _serviceType, bytes32 indexed _serviceVersion ); event ServiceTypeAdded( bytes32 indexed _serviceType, uint256 indexed _serviceTypeMin, uint256 indexed _serviceTypeMax ); event ServiceTypeRemoved(bytes32 indexed _serviceType); /** * @notice Function to initialize the contract * @param _governanceAddress - Governance proxy address */ function initialize(address _governanceAddress) public initializer { _updateGovernanceAddress(_governanceAddress); InitializableV2.initialize(); } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); } // ========================================= Service Type Logic ========================================= /** * @notice Add a new service type * @param _serviceType - type of service to add * @param _serviceTypeMin - minimum stake for service type * @param _serviceTypeMax - maximum stake for service type */ function addServiceType( bytes32 _serviceType, uint256 _serviceTypeMin, uint256 _serviceTypeMax ) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); require( !this.serviceTypeIsValid(_serviceType), "ServiceTypeManager: Already known service type" ); require( _serviceTypeMax > _serviceTypeMin, "ServiceTypeManager: Max stake must be non-zero and greater than min stake" ); // Ensure serviceType cannot be re-added if it previously existed and was removed // stored maxStake > 0 means it was previously added and removed require( serviceTypeInfo[_serviceType].maxStake == 0, "ServiceTypeManager: Cannot re-add serviceType after it was removed." ); validServiceTypes.push(_serviceType); serviceTypeInfo[_serviceType] = ServiceTypeInfo({ isValid: true, minStake: _serviceTypeMin, maxStake: _serviceTypeMax }); emit ServiceTypeAdded(_serviceType, _serviceTypeMin, _serviceTypeMax); } /** * @notice Remove an existing service type * @param _serviceType - name of service type to remove */ function removeServiceType(bytes32 _serviceType) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); uint256 serviceIndex = 0; bool foundService = false; for (uint256 i = 0; i < validServiceTypes.length; i ++) { if (validServiceTypes[i] == _serviceType) { serviceIndex = i; foundService = true; break; } } require(foundService == true, "ServiceTypeManager: Invalid service type, not found"); // Overwrite service index uint256 lastIndex = validServiceTypes.length - 1; validServiceTypes[serviceIndex] = validServiceTypes[lastIndex]; validServiceTypes.length--; // Mark as invalid serviceTypeInfo[_serviceType].isValid = false; // Note - stake bounds are not reset so they can be checked to prevent serviceType from being re-added emit ServiceTypeRemoved(_serviceType); } /** * @notice Get isValid, min and max stake for a given service type * @param _serviceType - type of service * @return isValid, min and max stake for type */ function getServiceTypeInfo(bytes32 _serviceType) external view returns (bool isValid, uint256 minStake, uint256 maxStake) { _requireIsInitialized(); return ( serviceTypeInfo[_serviceType].isValid, serviceTypeInfo[_serviceType].minStake, serviceTypeInfo[_serviceType].maxStake ); } /** * @notice Get list of valid service types */ function getValidServiceTypes() external view returns (bytes32[] memory) { _requireIsInitialized(); return validServiceTypes; } /** * @notice Return indicating whether this is a valid service type */ function serviceTypeIsValid(bytes32 _serviceType) external view returns (bool) { _requireIsInitialized(); return serviceTypeInfo[_serviceType].isValid; } // ========================================= Service Version Logic ========================================= /** * @notice Add new version for a serviceType * @param _serviceType - type of service * @param _serviceVersion - new version of service to add */ function setServiceVersion( bytes32 _serviceType, bytes32 _serviceVersion ) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); require(this.serviceTypeIsValid(_serviceType), "ServiceTypeManager: Invalid service type"); require( serviceTypeVersionInfo[_serviceType][_serviceVersion] == false, "ServiceTypeManager: Already registered" ); // Update array of known versions for type serviceTypeVersions[_serviceType].push(_serviceVersion); // Update status for this specific service version serviceTypeVersionInfo[_serviceType][_serviceVersion] = true; emit SetServiceVersion(_serviceType, _serviceVersion); } /** * @notice Get a version for a service type given it's index * @param _serviceType - type of service * @param _versionIndex - index in list of service versions * @return bytes32 value for serviceVersion */ function getVersion(bytes32 _serviceType, uint256 _versionIndex) external view returns (bytes32) { _requireIsInitialized(); require( serviceTypeVersions[_serviceType].length > _versionIndex, "ServiceTypeManager: No registered version of serviceType" ); return (serviceTypeVersions[_serviceType][_versionIndex]); } /** * @notice Get curent version for a service type * @param _serviceType - type of service * @return Returns current version of service */ function getCurrentVersion(bytes32 _serviceType) external view returns (bytes32) { _requireIsInitialized(); require( serviceTypeVersions[_serviceType].length >= 1, "ServiceTypeManager: No registered version of serviceType" ); uint256 latestVersionIndex = serviceTypeVersions[_serviceType].length - 1; return (serviceTypeVersions[_serviceType][latestVersionIndex]); } /** * @notice Get total number of versions for a service type * @param _serviceType - type of service */ function getNumberOfVersions(bytes32 _serviceType) external view returns (uint256) { _requireIsInitialized(); return serviceTypeVersions[_serviceType].length; } /** * @notice Return boolean indicating whether given version is valid for given type * @param _serviceType - type of service * @param _serviceVersion - version of service to check */ function serviceVersionIsValid(bytes32 _serviceType, bytes32 _serviceVersion) external view returns (bool) { _requireIsInitialized(); return serviceTypeVersionInfo[_serviceType][_serviceVersion]; } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "ServiceTypeManager: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } } // File: contracts/ClaimsManager.sol pragma solidity ^0.5.0; /// @notice ERC20 imported via Staking.sol /// @notice SafeERC20 imported via Staking.sol /// @notice Governance imported via Staking.sol /// @notice SafeMath imported via ServiceProviderFactory.sol /** * Designed to automate claim funding, minting tokens as necessary * @notice - will call InitializableV2 constructor */ contract ClaimsManager is InitializableV2 { using SafeMath for uint256; using SafeERC20 for ERC20; string private constant ERROR_ONLY_GOVERNANCE = ( "ClaimsManager: Only callable by Governance contract" ); address private governanceAddress; address private stakingAddress; address private serviceProviderFactoryAddress; address private delegateManagerAddress; /** * @notice - Minimum number of blocks between funding rounds * 604800 seconds / week * Avg block time - 13s * 604800 / 13 = 46523.0769231 blocks */ uint256 private fundingRoundBlockDiff; /** * @notice - Configures the current funding amount per round * Weekly rounds, 7% PA inflation = 70,000,000 new tokens in first year * = 70,000,000/365*7 (year is slightly more than a week) * = 1342465.75342 new AUDS per week * = 1342465753420000000000000 new wei units per week * @dev - Past a certain block height, this schedule will be updated * - Logic determining schedule will be sourced from an external contract */ uint256 private fundingAmount; // Denotes current round uint256 private roundNumber; // Staking contract ref ERC20Mintable private audiusToken; /// @dev - Address to which recurringCommunityFundingAmount is transferred at funding round start address private communityPoolAddress; /// @dev - Reward amount transferred to communityPoolAddress at funding round start uint256 private recurringCommunityFundingAmount; // Struct representing round state // 1) Block at which round was funded // 2) Total funded for this round // 3) Total claimed in round struct Round { uint256 fundedBlock; uint256 fundedAmount; uint256 totalClaimedInRound; } // Current round information Round private currentRound; event RoundInitiated( uint256 indexed _blockNumber, uint256 indexed _roundNumber, uint256 indexed _fundAmount ); event ClaimProcessed( address indexed _claimer, uint256 indexed _rewards, uint256 _oldTotal, uint256 indexed _newTotal ); event CommunityRewardsTransferred( address indexed _transferAddress, uint256 indexed _amount ); event FundingAmountUpdated(uint256 indexed _amount); event FundingRoundBlockDiffUpdated(uint256 indexed _blockDifference); event GovernanceAddressUpdated(address indexed _newGovernanceAddress); event StakingAddressUpdated(address indexed _newStakingAddress); event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress); event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress); event RecurringCommunityFundingAmountUpdated(uint256 indexed _amount); event CommunityPoolAddressUpdated(address indexed _newCommunityPoolAddress); /** * @notice Function to initialize the contract * @dev stakingAddress must be initialized separately after Staking contract is deployed * @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed * @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed * @param _tokenAddress - address of ERC20 token that will be claimed * @param _governanceAddress - address for Governance proxy contract */ function initialize( address _tokenAddress, address _governanceAddress ) public initializer { _updateGovernanceAddress(_governanceAddress); audiusToken = ERC20Mintable(_tokenAddress); fundingRoundBlockDiff = 46523; fundingAmount = 1342465753420000000000000; // 1342465.75342 AUDS roundNumber = 0; currentRound = Round({ fundedBlock: 0, fundedAmount: 0, totalClaimedInRound: 0 }); // Community pool funding amount and address initialized to zero recurringCommunityFundingAmount = 0; communityPoolAddress = address(0x0); InitializableV2.initialize(); } /// @notice Get the duration of a funding round in blocks function getFundingRoundBlockDiff() external view returns (uint256) { _requireIsInitialized(); return fundingRoundBlockDiff; } /// @notice Get the last block where a funding round was initiated function getLastFundedBlock() external view returns (uint256) { _requireIsInitialized(); return currentRound.fundedBlock; } /// @notice Get the amount funded per round in wei function getFundsPerRound() external view returns (uint256) { _requireIsInitialized(); return fundingAmount; } /// @notice Get the total amount claimed in the current round function getTotalClaimedInRound() external view returns (uint256) { _requireIsInitialized(); return currentRound.totalClaimedInRound; } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the DelegateManager address function getDelegateManagerAddress() external view returns (address) { _requireIsInitialized(); return delegateManagerAddress; } /** * @notice Get the Staking address */ function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } /** * @notice Get the community pool address */ function getCommunityPoolAddress() external view returns (address) { _requireIsInitialized(); return communityPoolAddress; } /** * @notice Get the community funding amount */ function getRecurringCommunityFundingAmount() external view returns (uint256) { _requireIsInitialized(); return recurringCommunityFundingAmount; } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); emit GovernanceAddressUpdated(_governanceAddress); } /** * @notice Set the Staking address * @dev Only callable by Governance address * @param _stakingAddress - address for new Staking contract */ function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _stakingAddress; emit StakingAddressUpdated(_stakingAddress); } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by Governance address * @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceProviderFactoryAddress = _serviceProviderFactoryAddress; emit ServiceProviderFactoryAddressUpdated(_serviceProviderFactoryAddress); } /** * @notice Set the DelegateManager address * @dev Only callable by Governance address * @param _delegateManagerAddress - address for new DelegateManager contract */ function setDelegateManagerAddress(address _delegateManagerAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); delegateManagerAddress = _delegateManagerAddress; emit DelegateManagerAddressUpdated(_delegateManagerAddress); } /** * @notice Start a new funding round * @dev Permissioned to be callable by stakers or governance contract */ function initiateRound() external { _requireIsInitialized(); _requireStakingAddressIsSet(); require( block.number.sub(currentRound.fundedBlock) > fundingRoundBlockDiff, "ClaimsManager: Required block difference not met" ); currentRound = Round({ fundedBlock: block.number, fundedAmount: fundingAmount, totalClaimedInRound: 0 }); roundNumber = roundNumber.add(1); /* * Transfer community funding amount to community pool address, if set */ if (recurringCommunityFundingAmount > 0 && communityPoolAddress != address(0x0)) { // ERC20Mintable always returns true audiusToken.mint(address(this), recurringCommunityFundingAmount); // Approve transfer to community pool address audiusToken.approve(communityPoolAddress, recurringCommunityFundingAmount); // Transfer to community pool address ERC20(address(audiusToken)).safeTransfer(communityPoolAddress, recurringCommunityFundingAmount); emit CommunityRewardsTransferred(communityPoolAddress, recurringCommunityFundingAmount); } emit RoundInitiated( currentRound.fundedBlock, roundNumber, currentRound.fundedAmount ); } /** * @notice Mints and stakes tokens on behalf of ServiceProvider + delegators * @dev Callable through DelegateManager by Service Provider * @param _claimer - service provider address * @param _totalLockedForSP - amount of tokens locked up across DelegateManager + ServiceProvider * @return minted rewards for this claimer */ function processClaim( address _claimer, uint256 _totalLockedForSP ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireDelegateManagerAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); require( msg.sender == delegateManagerAddress, "ClaimsManager: ProcessClaim only accessible to DelegateManager" ); Staking stakingContract = Staking(stakingAddress); // Prevent duplicate claim uint256 lastUserClaimBlock = stakingContract.lastClaimedFor(_claimer); require( lastUserClaimBlock <= currentRound.fundedBlock, "ClaimsManager: Claim already processed for user" ); uint256 totalStakedAtFundBlockForClaimer = stakingContract.totalStakedForAt( _claimer, currentRound.fundedBlock); (,,bool withinBounds,,,) = ( ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_claimer) ); // Once they claim the zero reward amount, stake can be modified once again // Subtract total locked amount for SP from stake at fund block uint256 totalActiveClaimerStake = totalStakedAtFundBlockForClaimer.sub(_totalLockedForSP); uint256 totalStakedAtFundBlock = stakingContract.totalStakedAt(currentRound.fundedBlock); // Calculate claimer rewards uint256 rewardsForClaimer = ( totalActiveClaimerStake.mul(fundingAmount) ).div(totalStakedAtFundBlock); // For a claimer violating bounds, no new tokens are minted // Claim history is marked to zero and function is short-circuited // Total rewards can be zero if all stake is currently locked up if (!withinBounds || rewardsForClaimer == 0) { stakingContract.updateClaimHistory(0, _claimer); emit ClaimProcessed( _claimer, 0, totalStakedAtFundBlockForClaimer, totalActiveClaimerStake ); return 0; } // ERC20Mintable always returns true audiusToken.mint(address(this), rewardsForClaimer); // Approve transfer to staking address for claimer rewards // ERC20 always returns true audiusToken.approve(stakingAddress, rewardsForClaimer); // Transfer rewards stakingContract.stakeRewards(rewardsForClaimer, _claimer); // Update round claim value currentRound.totalClaimedInRound = currentRound.totalClaimedInRound.add(rewardsForClaimer); // Update round claim value uint256 newTotal = stakingContract.totalStakedFor(_claimer); emit ClaimProcessed( _claimer, rewardsForClaimer, totalStakedAtFundBlockForClaimer, newTotal ); return rewardsForClaimer; } /** * @notice Modify funding amount per round * @param _newAmount - new amount to fund per round in wei */ function updateFundingAmount(uint256 _newAmount) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); fundingAmount = _newAmount; emit FundingAmountUpdated(_newAmount); } /** * @notice Returns boolean indicating whether a claim is considered pending * @dev Note that an address with no endpoints can never have a pending claim * @param _sp - address of the service provider to check * @return true if eligible for claim, false if not */ function claimPending(address _sp) external view returns (bool) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); uint256 lastClaimedForSP = Staking(stakingAddress).lastClaimedFor(_sp); (,,,uint256 numEndpoints,,) = ( ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_sp) ); return (lastClaimedForSP < currentRound.fundedBlock && numEndpoints > 0); } /** * @notice Modify minimum block difference between funding rounds * @param _newFundingRoundBlockDiff - new min block difference to set */ function updateFundingRoundBlockDiff(uint256 _newFundingRoundBlockDiff) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); emit FundingRoundBlockDiffUpdated(_newFundingRoundBlockDiff); fundingRoundBlockDiff = _newFundingRoundBlockDiff; } /** * @notice Modify community funding amound for each round * @param _newRecurringCommunityFundingAmount - new reward amount transferred to * communityPoolAddress at funding round start */ function updateRecurringCommunityFundingAmount( uint256 _newRecurringCommunityFundingAmount ) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); recurringCommunityFundingAmount = _newRecurringCommunityFundingAmount; emit RecurringCommunityFundingAmountUpdated(_newRecurringCommunityFundingAmount); } /** * @notice Modify community pool address * @param _newCommunityPoolAddress - new address to which recurringCommunityFundingAmount * is transferred at funding round start */ function updateCommunityPoolAddress(address _newCommunityPoolAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); communityPoolAddress = _newCommunityPoolAddress; emit CommunityPoolAddressUpdated(_newCommunityPoolAddress); } // ========================================= Private Functions ========================================= /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) private { require( Governance(_governanceAddress).isGovernanceAddress() == true, "ClaimsManager: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } function _requireStakingAddressIsSet() private view { require(stakingAddress != address(0x00), "ClaimsManager: stakingAddress is not set"); } function _requireDelegateManagerAddressIsSet() private view { require( delegateManagerAddress != address(0x00), "ClaimsManager: delegateManagerAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "ClaimsManager: serviceProviderFactoryAddress is not set" ); } } // File: contracts/ServiceProviderFactory.sol pragma solidity ^0.5.0; /// @notice Governance imported via Staking.sol contract ServiceProviderFactory is InitializableV2 { using SafeMath for uint256; /// @dev - denominator for deployer cut calculations /// @dev - user values are intended to be x/DEPLOYER_CUT_BASE uint256 private constant DEPLOYER_CUT_BASE = 100; string private constant ERROR_ONLY_GOVERNANCE = ( "ServiceProviderFactory: Only callable by Governance contract" ); string private constant ERROR_ONLY_SP_GOVERNANCE = ( "ServiceProviderFactory: Only callable by Service Provider or Governance" ); address private stakingAddress; address private delegateManagerAddress; address private governanceAddress; address private serviceTypeManagerAddress; address private claimsManagerAddress; /// @notice Period in blocks that a decrease stake operation is delayed. /// Must be greater than governance votingPeriod + executionDelay in order to /// prevent pre-emptive withdrawal in anticipation of a slash proposal uint256 private decreaseStakeLockupDuration; /// @notice Period in blocks that an update deployer cut operation is delayed. /// Must be greater than funding round block diff in order /// to prevent manipulation around a funding round uint256 private deployerCutLockupDuration; /// @dev - Stores following entities /// 1) Directly staked amount by SP, not including delegators /// 2) % Cut of delegator tokens taken during reward /// 3) Bool indicating whether this SP has met min/max requirements /// 4) Number of endpoints registered by SP /// 5) Minimum deployer stake for this service provider /// 6) Maximum total stake for this account struct ServiceProviderDetails { uint256 deployerStake; uint256 deployerCut; bool validBounds; uint256 numberOfEndpoints; uint256 minAccountStake; uint256 maxAccountStake; } /// @dev - Data structure for time delay during withdrawal struct DecreaseStakeRequest { uint256 decreaseAmount; uint256 lockupExpiryBlock; } /// @dev - Data structure for time delay during deployer cut update struct UpdateDeployerCutRequest { uint256 newDeployerCut; uint256 lockupExpiryBlock; } /// @dev - Struct maintaining information about sp /// @dev - blocknumber is block.number when endpoint registered struct ServiceEndpoint { address owner; string endpoint; uint256 blocknumber; address delegateOwnerWallet; } /// @dev - Mapping of service provider address to details mapping(address => ServiceProviderDetails) private spDetails; /// @dev - Uniquely assigned serviceProvider ID, incremented for each service type /// @notice - Keeps track of the total number of services registered regardless of /// whether some have been deregistered since mapping(bytes32 => uint256) private serviceProviderTypeIDs; /// @dev - mapping of (serviceType -> (serviceInstanceId <-> serviceProviderInfo)) /// @notice - stores the actual service provider data like endpoint and owner wallet /// with the ability lookup by service type and service id */ mapping(bytes32 => mapping(uint256 => ServiceEndpoint)) private serviceProviderInfo; /// @dev - mapping of keccak256(endpoint) to uint256 ID /// @notice - used to check if a endpoint has already been registered and also lookup /// the id of an endpoint mapping(bytes32 => uint256) private serviceProviderEndpointToId; /// @dev - mapping of address -> sp id array */ /// @notice - stores all the services registered by a provider. for each address, /// provides the ability to lookup by service type and see all registered services mapping(address => mapping(bytes32 => uint256[])) private serviceProviderAddressToId; /// @dev - Mapping of service provider -> decrease stake request mapping(address => DecreaseStakeRequest) private decreaseStakeRequests; /// @dev - Mapping of service provider -> update deployer cut requests mapping(address => UpdateDeployerCutRequest) private updateDeployerCutRequests; event RegisteredServiceProvider( uint256 indexed _spID, bytes32 indexed _serviceType, address indexed _owner, string _endpoint, uint256 _stakeAmount ); event DeregisteredServiceProvider( uint256 indexed _spID, bytes32 indexed _serviceType, address indexed _owner, string _endpoint, uint256 _unstakeAmount ); event IncreasedStake( address indexed _owner, uint256 indexed _increaseAmount, uint256 indexed _newStakeAmount ); event DecreaseStakeRequested( address indexed _owner, uint256 indexed _decreaseAmount, uint256 indexed _lockupExpiryBlock ); event DecreaseStakeRequestCancelled( address indexed _owner, uint256 indexed _decreaseAmount, uint256 indexed _lockupExpiryBlock ); event DecreaseStakeRequestEvaluated( address indexed _owner, uint256 indexed _decreaseAmount, uint256 indexed _newStakeAmount ); event EndpointUpdated( bytes32 indexed _serviceType, address indexed _owner, string _oldEndpoint, string _newEndpoint, uint256 indexed _spID ); event DelegateOwnerWalletUpdated( address indexed _owner, bytes32 indexed _serviceType, uint256 indexed _spID, address _updatedWallet ); event DeployerCutUpdateRequested( address indexed _owner, uint256 indexed _updatedCut, uint256 indexed _lockupExpiryBlock ); event DeployerCutUpdateRequestCancelled( address indexed _owner, uint256 indexed _requestedCut, uint256 indexed _finalCut ); event DeployerCutUpdateRequestEvaluated( address indexed _owner, uint256 indexed _updatedCut ); event DecreaseStakeLockupDurationUpdated(uint256 indexed _lockupDuration); event UpdateDeployerCutLockupDurationUpdated(uint256 indexed _lockupDuration); event GovernanceAddressUpdated(address indexed _newGovernanceAddress); event StakingAddressUpdated(address indexed _newStakingAddress); event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress); event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress); event ServiceTypeManagerAddressUpdated(address indexed _newServiceTypeManagerAddress); /** * @notice Function to initialize the contract * @dev stakingAddress must be initialized separately after Staking contract is deployed * @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed * @dev serviceTypeManagerAddress must be initialized separately after ServiceTypeManager contract is deployed * @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed * @param _governanceAddress - Governance proxy address */ function initialize ( address _governanceAddress, address _claimsManagerAddress, uint256 _decreaseStakeLockupDuration, uint256 _deployerCutLockupDuration ) public initializer { _updateGovernanceAddress(_governanceAddress); claimsManagerAddress = _claimsManagerAddress; _updateDecreaseStakeLockupDuration(_decreaseStakeLockupDuration); _updateDeployerCutLockupDuration(_deployerCutLockupDuration); InitializableV2.initialize(); } /** * @notice Register a new endpoint to the account of msg.sender * @dev Transfers stake from service provider into staking pool * @param _serviceType - type of service to register, must be valid in ServiceTypeManager * @param _endpoint - url of the service to register - url of the service to register * @param _stakeAmount - amount to stake, must be within bounds in ServiceTypeManager * @param _delegateOwnerWallet - wallet to delegate some permissions for some basic management properties * @return New service provider ID for this endpoint */ function register( bytes32 _serviceType, string calldata _endpoint, uint256 _stakeAmount, address _delegateOwnerWallet ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceTypeManagerAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( ServiceTypeManager(serviceTypeManagerAddress).serviceTypeIsValid(_serviceType), "ServiceProviderFactory: Valid service type required"); // Stake token amount from msg.sender if (_stakeAmount > 0) { require( !_claimPending(msg.sender), "ServiceProviderFactory: No pending claim expected" ); Staking(stakingAddress).stakeFor(msg.sender, _stakeAmount); } require ( serviceProviderEndpointToId[keccak256(bytes(_endpoint))] == 0, "ServiceProviderFactory: Endpoint already registered"); uint256 newServiceProviderID = serviceProviderTypeIDs[_serviceType].add(1); serviceProviderTypeIDs[_serviceType] = newServiceProviderID; // Index spInfo serviceProviderInfo[_serviceType][newServiceProviderID] = ServiceEndpoint({ owner: msg.sender, endpoint: _endpoint, blocknumber: block.number, delegateOwnerWallet: _delegateOwnerWallet }); // Update endpoint mapping serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID; // Update (address -> type -> ids[]) serviceProviderAddressToId[msg.sender][_serviceType].push(newServiceProviderID); // Increment number of endpoints for this address spDetails[msg.sender].numberOfEndpoints = spDetails[msg.sender].numberOfEndpoints.add(1); // Update deployer total spDetails[msg.sender].deployerStake = ( spDetails[msg.sender].deployerStake.add(_stakeAmount) ); // Update min and max totals for this service provider (, uint256 typeMin, uint256 typeMax) = ServiceTypeManager( serviceTypeManagerAddress ).getServiceTypeInfo(_serviceType); spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.add(typeMin); spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.add(typeMax); // Confirm both aggregate account balance and directly staked amount are valid this.validateAccountStakeBalance(msg.sender); uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender); // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; emit RegisteredServiceProvider( newServiceProviderID, _serviceType, msg.sender, _endpoint, currentlyStakedForOwner ); return newServiceProviderID; } /** * @notice Deregister an endpoint from the account of msg.sender * @dev Unstakes all tokens for service provider if this is the last endpoint * @param _serviceType - type of service to deregister * @param _endpoint - endpoint to deregister * @return spId of the service that was deregistered */ function deregister( bytes32 _serviceType, string calldata _endpoint ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceTypeManagerAddressIsSet(); // Unstake on deregistration if and only if this is the last service endpoint uint256 unstakeAmount = 0; bool unstaked = false; // owned by the service provider if (spDetails[msg.sender].numberOfEndpoints == 1) { unstakeAmount = spDetails[msg.sender].deployerStake; // Submit request to decrease stake, overriding any pending request decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({ decreaseAmount: unstakeAmount, lockupExpiryBlock: block.number.add(decreaseStakeLockupDuration) }); unstaked = true; } require ( serviceProviderEndpointToId[keccak256(bytes(_endpoint))] != 0, "ServiceProviderFactory: Endpoint not registered"); // Cache invalided service provider ID uint256 deregisteredID = serviceProviderEndpointToId[keccak256(bytes(_endpoint))]; // Update endpoint mapping serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = 0; require( keccak256(bytes(serviceProviderInfo[_serviceType][deregisteredID].endpoint)) == keccak256(bytes(_endpoint)), "ServiceProviderFactory: Invalid endpoint for service type"); require ( serviceProviderInfo[_serviceType][deregisteredID].owner == msg.sender, "ServiceProviderFactory: Only callable by endpoint owner"); // Update info mapping delete serviceProviderInfo[_serviceType][deregisteredID]; // Reset id, update array uint256 spTypeLength = serviceProviderAddressToId[msg.sender][_serviceType].length; for (uint256 i = 0; i < spTypeLength; i ++) { if (serviceProviderAddressToId[msg.sender][_serviceType][i] == deregisteredID) { // Overwrite element to be deleted with last element in array serviceProviderAddressToId[msg.sender][_serviceType][i] = serviceProviderAddressToId[msg.sender][_serviceType][spTypeLength - 1]; // Reduce array size, exit loop serviceProviderAddressToId[msg.sender][_serviceType].length--; // Confirm this ID has been found for the service provider break; } } // Decrement number of endpoints for this address spDetails[msg.sender].numberOfEndpoints -= 1; // Update min and max totals for this service provider (, uint256 typeMin, uint256 typeMax) = ServiceTypeManager( serviceTypeManagerAddress ).getServiceTypeInfo(_serviceType); spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.sub(typeMin); spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.sub(typeMax); emit DeregisteredServiceProvider( deregisteredID, _serviceType, msg.sender, _endpoint, unstakeAmount); // Confirm both aggregate account balance and directly staked amount are valid // Only if unstake operation has not occurred if (!unstaked) { this.validateAccountStakeBalance(msg.sender); // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; } return deregisteredID; } /** * @notice Increase stake for service provider * @param _increaseStakeAmount - amount to increase staked amount by * @return New total stake for service provider */ function increaseStake( uint256 _increaseStakeAmount ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireClaimsManagerAddressIsSet(); // Confirm owner has an endpoint require( spDetails[msg.sender].numberOfEndpoints > 0, "ServiceProviderFactory: Registered endpoint required to increase stake" ); require( !_claimPending(msg.sender), "ServiceProviderFactory: No claim expected to be pending prior to stake transfer" ); Staking stakingContract = Staking( stakingAddress ); // Stake increased token amount for msg.sender stakingContract.stakeFor(msg.sender, _increaseStakeAmount); uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender); // Update deployer total spDetails[msg.sender].deployerStake = ( spDetails[msg.sender].deployerStake.add(_increaseStakeAmount) ); // Confirm both aggregate account balance and directly staked amount are valid this.validateAccountStakeBalance(msg.sender); // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; emit IncreasedStake( msg.sender, _increaseStakeAmount, newStakeAmount ); return newStakeAmount; } /** * @notice Request to decrease stake. This sets a lockup for decreaseStakeLockupDuration after which the actual decreaseStake can be called * @dev Decreasing stake is only processed if a service provider is within valid bounds * @param _decreaseStakeAmount - amount to decrease stake by in wei * @return New total stake amount after the lockup */ function requestDecreaseStake(uint256 _decreaseStakeAmount) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( _decreaseStakeAmount > 0, "ServiceProviderFactory: Requested stake decrease amount must be greater than zero" ); require( !_claimPending(msg.sender), "ServiceProviderFactory: No claim expected to be pending prior to stake transfer" ); Staking stakingContract = Staking( stakingAddress ); uint256 currentStakeAmount = stakingContract.totalStakedFor(msg.sender); // Prohibit decreasing stake to invalid bounds _validateBalanceInternal(msg.sender, (currentStakeAmount.sub(_decreaseStakeAmount))); uint256 expiryBlock = block.number.add(decreaseStakeLockupDuration); decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({ decreaseAmount: _decreaseStakeAmount, lockupExpiryBlock: expiryBlock }); emit DecreaseStakeRequested(msg.sender, _decreaseStakeAmount, expiryBlock); return currentStakeAmount.sub(_decreaseStakeAmount); } /** * @notice Cancel a decrease stake request during the lockup * @dev Either called by the service provider via DelegateManager or governance during a slash action * @param _account - address of service provider */ function cancelDecreaseStakeRequest(address _account) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == _account || msg.sender == delegateManagerAddress, "ServiceProviderFactory: Only owner or DelegateManager" ); require( _decreaseRequestIsPending(_account), "ServiceProviderFactory: Decrease stake request must be pending" ); DecreaseStakeRequest memory cancelledRequest = decreaseStakeRequests[_account]; // Clear decrease stake request decreaseStakeRequests[_account] = DecreaseStakeRequest({ decreaseAmount: 0, lockupExpiryBlock: 0 }); emit DecreaseStakeRequestCancelled( _account, cancelledRequest.decreaseAmount, cancelledRequest.lockupExpiryBlock ); } /** * @notice Called by user to decrease a stake after waiting the appropriate lockup period. * @return New total stake after decrease */ function decreaseStake() external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); require( _decreaseRequestIsPending(msg.sender), "ServiceProviderFactory: Decrease stake request must be pending" ); require( decreaseStakeRequests[msg.sender].lockupExpiryBlock <= block.number, "ServiceProviderFactory: Lockup must be expired" ); Staking stakingContract = Staking( stakingAddress ); uint256 decreaseAmount = decreaseStakeRequests[msg.sender].decreaseAmount; // Decrease staked token amount for msg.sender stakingContract.unstakeFor(msg.sender, decreaseAmount); // Query current stake uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender); // Update deployer total spDetails[msg.sender].deployerStake = ( spDetails[msg.sender].deployerStake.sub(decreaseAmount) ); // Confirm both aggregate account balance and directly staked amount are valid // During registration this validation is bypassed since no endpoints remain if (spDetails[msg.sender].numberOfEndpoints > 0) { this.validateAccountStakeBalance(msg.sender); } // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; // Clear decrease stake request delete decreaseStakeRequests[msg.sender]; emit DecreaseStakeRequestEvaluated(msg.sender, decreaseAmount, newStakeAmount); return newStakeAmount; } /** * @notice Update delegate owner wallet for a given endpoint * @param _serviceType - type of service to register, must be valid in ServiceTypeManager * @param _endpoint - url of the service to register - url of the service to register * @param _updatedDelegateOwnerWallet - address of new delegate wallet */ function updateDelegateOwnerWallet( bytes32 _serviceType, string calldata _endpoint, address _updatedDelegateOwnerWallet ) external { _requireIsInitialized(); uint256 spID = this.getServiceProviderIdFromEndpoint(_endpoint); require( serviceProviderInfo[_serviceType][spID].owner == msg.sender, "ServiceProviderFactory: Invalid update operation, wrong owner" ); serviceProviderInfo[_serviceType][spID].delegateOwnerWallet = _updatedDelegateOwnerWallet; emit DelegateOwnerWalletUpdated( msg.sender, _serviceType, spID, _updatedDelegateOwnerWallet ); } /** * @notice Update the endpoint for a given service * @param _serviceType - type of service to register, must be valid in ServiceTypeManager * @param _oldEndpoint - old endpoint currently registered * @param _newEndpoint - new endpoint to replace old endpoint * @return ID of updated service provider */ function updateEndpoint( bytes32 _serviceType, string calldata _oldEndpoint, string calldata _newEndpoint ) external returns (uint256) { _requireIsInitialized(); uint256 spId = this.getServiceProviderIdFromEndpoint(_oldEndpoint); require ( spId != 0, "ServiceProviderFactory: Could not find service provider with that endpoint" ); ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][spId]; require( serviceEndpoint.owner == msg.sender, "ServiceProviderFactory: Invalid update endpoint operation, wrong owner" ); require( keccak256(bytes(serviceEndpoint.endpoint)) == keccak256(bytes(_oldEndpoint)), "ServiceProviderFactory: Old endpoint doesn't match what's registered for the service provider" ); // invalidate old endpoint serviceProviderEndpointToId[keccak256(bytes(serviceEndpoint.endpoint))] = 0; // update to new endpoint serviceEndpoint.endpoint = _newEndpoint; serviceProviderInfo[_serviceType][spId] = serviceEndpoint; serviceProviderEndpointToId[keccak256(bytes(_newEndpoint))] = spId; emit EndpointUpdated(_serviceType, msg.sender, _oldEndpoint, _newEndpoint, spId); return spId; } /** * @notice Update the deployer cut for a given service provider * @param _serviceProvider - address of service provider * @param _cut - new value for deployer cut */ function requestUpdateDeployerCut(address _serviceProvider, uint256 _cut) external { _requireIsInitialized(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( (updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock == 0) && (updateDeployerCutRequests[_serviceProvider].newDeployerCut == 0), "ServiceProviderFactory: Update deployer cut operation pending" ); require( _cut <= DEPLOYER_CUT_BASE, "ServiceProviderFactory: Service Provider cut cannot exceed base value" ); uint256 expiryBlock = block.number + deployerCutLockupDuration; updateDeployerCutRequests[_serviceProvider] = UpdateDeployerCutRequest({ lockupExpiryBlock: expiryBlock, newDeployerCut: _cut }); emit DeployerCutUpdateRequested(_serviceProvider, _cut, expiryBlock); } /** * @notice Cancel a pending request to update deployer cut * @param _serviceProvider - address of service provider */ function cancelUpdateDeployerCut(address _serviceProvider) external { _requireIsInitialized(); _requirePendingDeployerCutOperation(_serviceProvider); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); UpdateDeployerCutRequest memory cancelledRequest = ( updateDeployerCutRequests[_serviceProvider] ); // Zero out request information delete updateDeployerCutRequests[_serviceProvider]; emit DeployerCutUpdateRequestCancelled( _serviceProvider, cancelledRequest.newDeployerCut, spDetails[_serviceProvider].deployerCut ); } /** * @notice Evalue request to update service provider cut of claims * @notice Update service provider cut as % of delegate claim, divided by the deployerCutBase. * @dev SPs will interact with this value as a percent, value translation done client side @dev A value of 5 dictates a 5% cut, with ( 5 / 100 ) * delegateReward going to an SP from each delegator each round. */ function updateDeployerCut(address _serviceProvider) external { _requireIsInitialized(); _requirePendingDeployerCutOperation(_serviceProvider); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock <= block.number, "ServiceProviderFactory: Lockup must be expired" ); spDetails[_serviceProvider].deployerCut = ( updateDeployerCutRequests[_serviceProvider].newDeployerCut ); // Zero out request information delete updateDeployerCutRequests[_serviceProvider]; emit DeployerCutUpdateRequestEvaluated( _serviceProvider, spDetails[_serviceProvider].deployerCut ); } /** * @notice Update service provider balance * @dev Called by DelegateManager by functions modifying entire stake like claim and slash * @param _serviceProvider - address of service provider * @param _amount - new amount of direct state for service provider */ function updateServiceProviderStake( address _serviceProvider, uint256 _amount ) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireDelegateManagerAddressIsSet(); require( msg.sender == delegateManagerAddress, "ServiceProviderFactory: only callable by DelegateManager" ); // Update SP tracked total spDetails[_serviceProvider].deployerStake = _amount; _updateServiceProviderBoundStatus(_serviceProvider); } /// @notice Update service provider lockup duration function updateDecreaseStakeLockupDuration(uint256 _duration) external { _requireIsInitialized(); require( msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE ); _updateDecreaseStakeLockupDuration(_duration); emit DecreaseStakeLockupDurationUpdated(_duration); } /// @notice Update service provider lockup duration function updateDeployerCutLockupDuration(uint256 _duration) external { _requireIsInitialized(); require( msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE ); _updateDeployerCutLockupDuration(_duration); emit UpdateDeployerCutLockupDurationUpdated(_duration); } /// @notice Get denominator for deployer cut calculations function getServiceProviderDeployerCutBase() external view returns (uint256) { _requireIsInitialized(); return DEPLOYER_CUT_BASE; } /// @notice Get current deployer cut update lockup duration function getDeployerCutLockupDuration() external view returns (uint256) { _requireIsInitialized(); return deployerCutLockupDuration; } /// @notice Get total number of service providers for a given serviceType function getTotalServiceTypeProviders(bytes32 _serviceType) external view returns (uint256) { _requireIsInitialized(); return serviceProviderTypeIDs[_serviceType]; } /// @notice Get service provider id for an endpoint function getServiceProviderIdFromEndpoint(string calldata _endpoint) external view returns (uint256) { _requireIsInitialized(); return serviceProviderEndpointToId[keccak256(bytes(_endpoint))]; } /** * @notice Get service provider ids for a given service provider and service type * @return List of service ids of that type for a service provider */ function getServiceProviderIdsFromAddress(address _ownerAddress, bytes32 _serviceType) external view returns (uint256[] memory) { _requireIsInitialized(); return serviceProviderAddressToId[_ownerAddress][_serviceType]; } /** * @notice Get information about a service endpoint given its service id * @param _serviceType - type of service, must be a valid service from ServiceTypeManager * @param _serviceId - id of service */ function getServiceEndpointInfo(bytes32 _serviceType, uint256 _serviceId) external view returns (address owner, string memory endpoint, uint256 blockNumber, address delegateOwnerWallet) { _requireIsInitialized(); ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][_serviceId]; return ( serviceEndpoint.owner, serviceEndpoint.endpoint, serviceEndpoint.blocknumber, serviceEndpoint.delegateOwnerWallet ); } /** * @notice Get information about a service provider given their address * @param _serviceProvider - address of service provider */ function getServiceProviderDetails(address _serviceProvider) external view returns ( uint256 deployerStake, uint256 deployerCut, bool validBounds, uint256 numberOfEndpoints, uint256 minAccountStake, uint256 maxAccountStake) { _requireIsInitialized(); return ( spDetails[_serviceProvider].deployerStake, spDetails[_serviceProvider].deployerCut, spDetails[_serviceProvider].validBounds, spDetails[_serviceProvider].numberOfEndpoints, spDetails[_serviceProvider].minAccountStake, spDetails[_serviceProvider].maxAccountStake ); } /** * @notice Get information about pending decrease stake requests for service provider * @param _serviceProvider - address of service provider */ function getPendingDecreaseStakeRequest(address _serviceProvider) external view returns (uint256 amount, uint256 lockupExpiryBlock) { _requireIsInitialized(); return ( decreaseStakeRequests[_serviceProvider].decreaseAmount, decreaseStakeRequests[_serviceProvider].lockupExpiryBlock ); } /** * @notice Get information about pending decrease stake requests for service provider * @param _serviceProvider - address of service provider */ function getPendingUpdateDeployerCutRequest(address _serviceProvider) external view returns (uint256 newDeployerCut, uint256 lockupExpiryBlock) { _requireIsInitialized(); return ( updateDeployerCutRequests[_serviceProvider].newDeployerCut, updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock ); } /// @notice Get current unstake lockup duration function getDecreaseStakeLockupDuration() external view returns (uint256) { _requireIsInitialized(); return decreaseStakeLockupDuration; } /** * @notice Validate that the total service provider balance is between the min and max stakes for all their registered services and validate direct stake for sp is above minimum * @param _serviceProvider - address of service provider */ function validateAccountStakeBalance(address _serviceProvider) external view { _requireIsInitialized(); _requireStakingAddressIsSet(); _validateBalanceInternal( _serviceProvider, Staking(stakingAddress).totalStakedFor(_serviceProvider) ); } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the Staking address function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } /// @notice Get the DelegateManager address function getDelegateManagerAddress() external view returns (address) { _requireIsInitialized(); return delegateManagerAddress; } /// @notice Get the ServiceTypeManager address function getServiceTypeManagerAddress() external view returns (address) { _requireIsInitialized(); return serviceTypeManagerAddress; } /// @notice Get the ClaimsManager address function getClaimsManagerAddress() external view returns (address) { _requireIsInitialized(); return claimsManagerAddress; } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); emit GovernanceAddressUpdated(_governanceAddress); } /** * @notice Set the Staking address * @dev Only callable by Governance address * @param _address - address for new Staking contract */ function setStakingAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _address; emit StakingAddressUpdated(_address); } /** * @notice Set the DelegateManager address * @dev Only callable by Governance address * @param _address - address for new DelegateManager contract */ function setDelegateManagerAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); delegateManagerAddress = _address; emit DelegateManagerAddressUpdated(_address); } /** * @notice Set the ServiceTypeManager address * @dev Only callable by Governance address * @param _address - address for new ServiceTypeManager contract */ function setServiceTypeManagerAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceTypeManagerAddress = _address; emit ServiceTypeManagerAddressUpdated(_address); } /** * @notice Set the ClaimsManager address * @dev Only callable by Governance address * @param _address - address for new ClaimsManager contract */ function setClaimsManagerAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); claimsManagerAddress = _address; emit ClaimsManagerAddressUpdated(_address); } // ========================================= Internal Functions ========================================= /** * @notice Update status in spDetails if the bounds for a service provider is valid */ function _updateServiceProviderBoundStatus(address _serviceProvider) internal { // Validate bounds for total stake uint256 totalSPStake = Staking(stakingAddress).totalStakedFor(_serviceProvider); if (totalSPStake < spDetails[_serviceProvider].minAccountStake || totalSPStake > spDetails[_serviceProvider].maxAccountStake) { // Indicate this service provider is out of bounds spDetails[_serviceProvider].validBounds = false; } else { // Indicate this service provider is within bounds spDetails[_serviceProvider].validBounds = true; } } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "ServiceProviderFactory: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } /** * @notice Set the deployer cut lockup duration * @param _duration - incoming duration */ function _updateDeployerCutLockupDuration(uint256 _duration) internal { require( ClaimsManager(claimsManagerAddress).getFundingRoundBlockDiff() < _duration, "ServiceProviderFactory: Incoming duration must be greater than funding round block diff" ); deployerCutLockupDuration = _duration; } /** * @notice Set the decrease stake lockup duration * @param _duration - incoming duration */ function _updateDecreaseStakeLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "ServiceProviderFactory: decreaseStakeLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); decreaseStakeLockupDuration = _duration; } /** * @notice Compare a given amount input against valid min and max bounds for service provider * @param _serviceProvider - address of service provider * @param _amount - amount in wei to compare */ function _validateBalanceInternal(address _serviceProvider, uint256 _amount) internal view { require( _amount <= spDetails[_serviceProvider].maxAccountStake, "ServiceProviderFactory: Maximum stake amount exceeded" ); require( spDetails[_serviceProvider].deployerStake >= spDetails[_serviceProvider].minAccountStake, "ServiceProviderFactory: Minimum stake requirement not met" ); } /** * @notice Get whether a decrease request has been initiated for service provider * @param _serviceProvider - address of service provider * return Boolean of whether decrease request has been initiated */ function _decreaseRequestIsPending(address _serviceProvider) internal view returns (bool) { return ( (decreaseStakeRequests[_serviceProvider].lockupExpiryBlock > 0) && (decreaseStakeRequests[_serviceProvider].decreaseAmount > 0) ); } /** * @notice Boolean indicating whether a claim is pending for this service provider */ /** * @notice Get whether a claim is pending for this service provider * @param _serviceProvider - address of service provider * return Boolean of whether claim is pending */ function _claimPending(address _serviceProvider) internal view returns (bool) { return ClaimsManager(claimsManagerAddress).claimPending(_serviceProvider); } // ========================================= Private Functions ========================================= function _requirePendingDeployerCutOperation (address _serviceProvider) private view { require( (updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock != 0), "ServiceProviderFactory: No update deployer cut operation pending" ); } function _requireStakingAddressIsSet() private view { require( stakingAddress != address(0x00), "ServiceProviderFactory: stakingAddress is not set" ); } function _requireDelegateManagerAddressIsSet() private view { require( delegateManagerAddress != address(0x00), "ServiceProviderFactory: delegateManagerAddress is not set" ); } function _requireServiceTypeManagerAddressIsSet() private view { require( serviceTypeManagerAddress != address(0x00), "ServiceProviderFactory: serviceTypeManagerAddress is not set" ); } function _requireClaimsManagerAddressIsSet() private view { require( claimsManagerAddress != address(0x00), "ServiceProviderFactory: claimsManagerAddress is not set" ); } } // File: contracts/DelegateManager.sol pragma solidity ^0.5.0; /// @notice SafeMath imported via ServiceProviderFactory.sol /// @notice Governance imported via Staking.sol /** * Designed to manage delegation to staking contract */ contract DelegateManagerV2 is InitializableV2 { using SafeMath for uint256; string private constant ERROR_ONLY_GOVERNANCE = ( "DelegateManager: Only callable by Governance contract" ); string private constant ERROR_MINIMUM_DELEGATION = ( "DelegateManager: Minimum delegation amount required" ); string private constant ERROR_ONLY_SP_GOVERNANCE = ( "DelegateManager: Only callable by target SP or governance" ); string private constant ERROR_DELEGATOR_STAKE = ( "DelegateManager: Delegator must be staked for SP" ); address private governanceAddress; address private stakingAddress; address private serviceProviderFactoryAddress; address private claimsManagerAddress; /** * Period in blocks an undelegate operation is delayed. * The undelegate operation speed bump is to prevent a delegator from * attempting to remove their delegation in anticipation of a slash. * @notice Must be greater than governance votingPeriod + executionDelay */ uint256 private undelegateLockupDuration; /// @notice Maximum number of delegators a single account can handle uint256 private maxDelegators; /// @notice Minimum amount of delegation allowed uint256 private minDelegationAmount; /** * Lockup duration for a remove delegator request. * The remove delegator speed bump is to prevent a service provider from maliciously * removing a delegator prior to the evaluation of a proposal. * @notice Must be greater than governance votingPeriod + executionDelay */ uint256 private removeDelegatorLockupDuration; /** * Evaluation period for a remove delegator request * @notice added to expiry block calculated for removeDelegatorLockupDuration */ uint256 private removeDelegatorEvalDuration; // Staking contract ref ERC20Mintable private audiusToken; // Struct representing total delegated to SP and list of delegators struct ServiceProviderDelegateInfo { uint256 totalDelegatedStake; uint256 totalLockedUpStake; address[] delegators; } // Data structures for lockup during withdrawal struct UndelegateStakeRequest { address serviceProvider; uint256 amount; uint256 lockupExpiryBlock; } // Service provider address -> ServiceProviderDelegateInfo mapping (address => ServiceProviderDelegateInfo) private spDelegateInfo; // Delegator stake by address delegated to // delegator -> (service provider -> delegatedStake) mapping (address => mapping(address => uint256)) private delegateInfo; // Delegator stake total by address // delegator -> (totalDelegated) // Note - delegator properties are maintained in a mapping instead of struct // in order to facilitate extensibility in the future. mapping (address => uint256) private delegatorTotalStake; // Requester to pending undelegate request mapping (address => UndelegateStakeRequest) private undelegateRequests; // Pending remove delegator requests // service provider -> (delegator -> lockupExpiryBlock) mapping (address => mapping (address => uint256)) private removeDelegatorRequests; event IncreaseDelegatedStake( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _increaseAmount ); event UndelegateStakeRequested( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount, uint256 _lockupExpiryBlock ); event UndelegateStakeRequestCancelled( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount ); event UndelegateStakeRequestEvaluated( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount ); event Claim( address indexed _claimer, uint256 indexed _rewards, uint256 indexed _newTotal ); event Slash( address indexed _target, uint256 indexed _amount, uint256 indexed _newTotal ); event RemoveDelegatorRequested( address indexed _serviceProvider, address indexed _delegator, uint256 indexed _lockupExpiryBlock ); event RemoveDelegatorRequestCancelled( address indexed _serviceProvider, address indexed _delegator ); event RemoveDelegatorRequestEvaluated( address indexed _serviceProvider, address indexed _delegator, uint256 indexed _unstakedAmount ); event MaxDelegatorsUpdated(uint256 indexed _maxDelegators); event MinDelegationUpdated(uint256 indexed _minDelegationAmount); event UndelegateLockupDurationUpdated(uint256 indexed _undelegateLockupDuration); event GovernanceAddressUpdated(address indexed _newGovernanceAddress); event StakingAddressUpdated(address indexed _newStakingAddress); event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress); event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress); event RemoveDelegatorLockupDurationUpdated(uint256 indexed _removeDelegatorLockupDuration); event RemoveDelegatorEvalDurationUpdated(uint256 indexed _removeDelegatorEvalDuration); // ========================================= New State Variables ========================================= string private constant ERROR_ONLY_SERVICE_PROVIDER = ( "DelegateManager: Only callable by valid Service Provider" ); // minDelegationAmount per service provider mapping (address => uint256) private spMinDelegationAmounts; event SPMinDelegationAmountUpdated( address indexed _serviceProvider, uint256 indexed _spMinDelegationAmount ); // ========================================= Modifier Functions ========================================= /** * @notice Function to initialize the contract * @dev stakingAddress must be initialized separately after Staking contract is deployed * @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed * @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed * @param _tokenAddress - address of ERC20 token that will be claimed * @param _governanceAddress - Governance proxy address */ function initialize ( address _tokenAddress, address _governanceAddress, uint256 _undelegateLockupDuration ) public initializer { _updateGovernanceAddress(_governanceAddress); audiusToken = ERC20Mintable(_tokenAddress); maxDelegators = 175; // Default minimum delegation amount set to 100AUD minDelegationAmount = 100 * 10**uint256(18); InitializableV2.initialize(); _updateUndelegateLockupDuration(_undelegateLockupDuration); // 1 week = 168hrs * 60 min/hr * 60 sec/min / ~13 sec/block = 46523 blocks _updateRemoveDelegatorLockupDuration(46523); // 24hr * 60min/hr * 60sec/min / ~13 sec/block = 6646 blocks removeDelegatorEvalDuration = 6646; } /** * @notice Allow a delegator to delegate stake to a service provider * @param _targetSP - address of service provider to delegate to * @param _amount - amount in wei to delegate * @return Updated total amount delegated to the service provider by delegator */ function delegateStake( address _targetSP, uint256 _amount ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( !_claimPending(_targetSP), "DelegateManager: Delegation not permitted for SP pending claim" ); address delegator = msg.sender; Staking stakingContract = Staking(stakingAddress); // Stake on behalf of target service provider stakingContract.delegateStakeFor( _targetSP, delegator, _amount ); // Update list of delegators to SP if necessary if (!_delegatorExistsForSP(delegator, _targetSP)) { // If not found, update list of delegates spDelegateInfo[_targetSP].delegators.push(delegator); require( spDelegateInfo[_targetSP].delegators.length <= maxDelegators, "DelegateManager: Maximum delegators exceeded" ); } // Update following values in storage through helper // totalServiceProviderDelegatedStake = current sp total + new amount, // totalStakedForSpFromDelegator = current delegator total for sp + new amount, // totalDelegatorStake = current delegator total + new amount _updateDelegatorStake( delegator, _targetSP, spDelegateInfo[_targetSP].totalDelegatedStake.add(_amount), delegateInfo[delegator][_targetSP].add(_amount), delegatorTotalStake[delegator].add(_amount) ); // Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount // since spMinDelegationAmount by default is 0 require( (delegateInfo[delegator][_targetSP] >= minDelegationAmount && delegateInfo[delegator][_targetSP] >= spMinDelegationAmounts[_targetSP] ), ERROR_MINIMUM_DELEGATION ); // Validate balance ServiceProviderFactory( serviceProviderFactoryAddress ).validateAccountStakeBalance(_targetSP); emit IncreaseDelegatedStake( delegator, _targetSP, _amount ); // Return new total return delegateInfo[delegator][_targetSP]; } /** * @notice Submit request for undelegation * @param _target - address of service provider to undelegate stake from * @param _amount - amount in wei to undelegate * @return Updated total amount delegated to the service provider by delegator */ function requestUndelegateStake( address _target, uint256 _amount ) external returns (uint256) { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( _amount > 0, "DelegateManager: Requested undelegate stake amount must be greater than zero" ); require( !_claimPending(_target), "DelegateManager: Undelegate request not permitted for SP pending claim" ); address delegator = msg.sender; require( _delegatorExistsForSP(delegator, _target), ERROR_DELEGATOR_STAKE ); // Confirm no pending delegation request require( !_undelegateRequestIsPending(delegator), "DelegateManager: No pending lockup expected" ); // Ensure valid bounds uint256 currentlyDelegatedToSP = delegateInfo[delegator][_target]; require( _amount <= currentlyDelegatedToSP, "DelegateManager: Cannot decrease greater than currently staked for this ServiceProvider" ); // Submit updated request for sender, with target sp, undelegate amount, target expiry block uint256 lockupExpiryBlock = block.number.add(undelegateLockupDuration); _updateUndelegateStakeRequest( delegator, _target, _amount, lockupExpiryBlock ); // Update total locked for this service provider, increasing by unstake amount _updateServiceProviderLockupAmount( _target, spDelegateInfo[_target].totalLockedUpStake.add(_amount) ); emit UndelegateStakeRequested(delegator, _target, _amount, lockupExpiryBlock); return delegateInfo[delegator][_target].sub(_amount); } /** * @notice Cancel undelegation request */ function cancelUndelegateStakeRequest() external { _requireIsInitialized(); address delegator = msg.sender; // Confirm pending delegation request require( _undelegateRequestIsPending(delegator), "DelegateManager: Pending lockup expected" ); uint256 unstakeAmount = undelegateRequests[delegator].amount; address unlockFundsSP = undelegateRequests[delegator].serviceProvider; // Update total locked for this service provider, decreasing by unstake amount _updateServiceProviderLockupAmount( unlockFundsSP, spDelegateInfo[unlockFundsSP].totalLockedUpStake.sub(unstakeAmount) ); // Remove pending request _resetUndelegateStakeRequest(delegator); emit UndelegateStakeRequestCancelled(delegator, unlockFundsSP, unstakeAmount); } /** * @notice Finalize undelegation request and withdraw stake * @return New total amount currently staked after stake has been undelegated */ function undelegateStake() external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); address delegator = msg.sender; // Confirm pending delegation request require( _undelegateRequestIsPending(delegator), "DelegateManager: Pending lockup expected" ); // Confirm lockup expiry has expired require( undelegateRequests[delegator].lockupExpiryBlock <= block.number, "DelegateManager: Lockup must be expired" ); // Confirm no pending claim for this service provider require( !_claimPending(undelegateRequests[delegator].serviceProvider), "DelegateManager: Undelegate not permitted for SP pending claim" ); address serviceProvider = undelegateRequests[delegator].serviceProvider; uint256 unstakeAmount = undelegateRequests[delegator].amount; // Unstake on behalf of target service provider Staking(stakingAddress).undelegateStakeFor( serviceProvider, delegator, unstakeAmount ); // Update total delegated for SP // totalServiceProviderDelegatedStake - total amount delegated to service provider // totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider _updateDelegatorStake( delegator, serviceProvider, spDelegateInfo[serviceProvider].totalDelegatedStake.sub(unstakeAmount), delegateInfo[delegator][serviceProvider].sub(unstakeAmount), delegatorTotalStake[delegator].sub(unstakeAmount) ); // Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount // since spMinDelegationAmount by default is 0 // Only exception is when delegating entire stake down to 0 require( ( delegateInfo[delegator][serviceProvider] >= minDelegationAmount && delegateInfo[delegator][serviceProvider] >= spMinDelegationAmounts[serviceProvider] ) || delegateInfo[delegator][serviceProvider] == 0, ERROR_MINIMUM_DELEGATION ); // Remove from delegators list if no delegated stake remaining if (delegateInfo[delegator][serviceProvider] == 0) { _removeFromDelegatorsList(serviceProvider, delegator); } // Update total locked for this service provider, decreasing by unstake amount _updateServiceProviderLockupAmount( serviceProvider, spDelegateInfo[serviceProvider].totalLockedUpStake.sub(unstakeAmount) ); // Reset undelegate request _resetUndelegateStakeRequest(delegator); emit UndelegateStakeRequestEvaluated( delegator, serviceProvider, unstakeAmount ); // Need to update service provider's `validBounds` flag // Only way to do this is through `SPFactory.updateServiceProviderStake()` // So we call it with the existing `spDeployerStake` (uint256 spDeployerStake,,,,,) = ( ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(serviceProvider) ); ServiceProviderFactory(serviceProviderFactoryAddress).updateServiceProviderStake( serviceProvider, spDeployerStake ); // Return new total return delegateInfo[delegator][serviceProvider]; } /** * @notice Claim and distribute rewards to delegators and service provider as necessary * @param _serviceProvider - Provider for which rewards are being distributed * @dev Factors in service provider rewards from delegator and transfers deployer cut */ function claimRewards(address _serviceProvider) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); // Total rewards = (balance in staking) - ((balance in sp factory) + (balance in delegate manager)) ( uint256 totalBalanceInStaking, uint256 totalBalanceInSPFactory, uint256 totalActiveFunds, uint256 totalRewards, uint256 deployerCut ) = _validateClaimRewards(spFactory, _serviceProvider); // No-op if balance is already equivalent // This case can occur if no rewards due to bound violation or all stake is locked if (totalRewards == 0) { return; } uint256 totalDelegatedStakeIncrease = _distributeDelegateRewards( _serviceProvider, totalActiveFunds, totalRewards, deployerCut, spFactory.getServiceProviderDeployerCutBase() ); // Update total delegated to this SP spDelegateInfo[_serviceProvider].totalDelegatedStake = ( spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease) ); // spRewardShare represents rewards directly allocated to service provider for their stake // Value is computed as the remainder of total minted rewards after distribution to // delegators, eliminating any potential for precision loss. uint256 spRewardShare = totalRewards.sub(totalDelegatedStakeIncrease); // Adding the newly calculated reward share to current balance uint256 newSPFactoryBalance = totalBalanceInSPFactory.add(spRewardShare); require( totalBalanceInStaking == newSPFactoryBalance.add(spDelegateInfo[_serviceProvider].totalDelegatedStake), "DelegateManager: claimRewards amount mismatch" ); spFactory.updateServiceProviderStake( _serviceProvider, newSPFactoryBalance ); } /** * @notice Reduce current stake amount * @dev Only callable by governance. Slashes service provider and delegators equally * @param _amount - amount in wei to slash * @param _slashAddress - address of service provider to slash */ function slash(uint256 _amount, address _slashAddress) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); Staking stakingContract = Staking(stakingAddress); ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); // Amount stored in staking contract for owner uint256 totalBalanceInStakingPreSlash = stakingContract.totalStakedFor(_slashAddress); require( (totalBalanceInStakingPreSlash >= _amount), "DelegateManager: Cannot slash more than total currently staked" ); // Cancel any withdrawal request for this service provider (uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_slashAddress); if (spLockedStake > 0) { spFactory.cancelDecreaseStakeRequest(_slashAddress); } // Amount in sp factory for slash target (uint256 totalBalanceInSPFactory,,,,,) = ( spFactory.getServiceProviderDetails(_slashAddress) ); require( totalBalanceInSPFactory > 0, "DelegateManager: Service Provider stake required" ); // Decrease value in Staking contract // A value of zero slash will fail in staking, reverting this transaction stakingContract.slash(_amount, _slashAddress); uint256 totalBalanceInStakingAfterSlash = stakingContract.totalStakedFor(_slashAddress); // Emit slash event emit Slash(_slashAddress, _amount, totalBalanceInStakingAfterSlash); uint256 totalDelegatedStakeDecrease = 0; // For each delegator and deployer, recalculate new value // newStakeAmount = newStakeAmount * (oldStakeAmount / totalBalancePreSlash) for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) { address delegator = spDelegateInfo[_slashAddress].delegators[i]; uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress]; uint256 newDelegateStake = ( totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake) ).div(totalBalanceInStakingPreSlash); // slashAmountForDelegator = preSlashDelegateStake - newDelegateStake; delegateInfo[delegator][_slashAddress] = ( delegateInfo[delegator][_slashAddress].sub(preSlashDelegateStake.sub(newDelegateStake)) ); // Update total stake for delegator _updateDelegatorTotalStake( delegator, delegatorTotalStake[delegator].sub(preSlashDelegateStake.sub(newDelegateStake)) ); // Update total decrease amount totalDelegatedStakeDecrease = ( totalDelegatedStakeDecrease.add(preSlashDelegateStake.sub(newDelegateStake)) ); // Check for any locked up funds for this slashed delegator // Slash overrides any pending withdrawal requests if (undelegateRequests[delegator].amount != 0) { address unstakeSP = undelegateRequests[delegator].serviceProvider; uint256 unstakeAmount = undelegateRequests[delegator].amount; // Remove pending request _updateServiceProviderLockupAmount( unstakeSP, spDelegateInfo[unstakeSP].totalLockedUpStake.sub(unstakeAmount) ); _resetUndelegateStakeRequest(delegator); } } // Update total delegated to this SP spDelegateInfo[_slashAddress].totalDelegatedStake = ( spDelegateInfo[_slashAddress].totalDelegatedStake.sub(totalDelegatedStakeDecrease) ); // Remaining decrease applied to service provider uint256 totalStakeDecrease = ( totalBalanceInStakingPreSlash.sub(totalBalanceInStakingAfterSlash) ); uint256 totalSPFactoryBalanceDecrease = ( totalStakeDecrease.sub(totalDelegatedStakeDecrease) ); spFactory.updateServiceProviderStake( _slashAddress, totalBalanceInSPFactory.sub(totalSPFactoryBalanceDecrease) ); } /** * @notice Initiate forcible removal of a delegator * @param _serviceProvider - address of service provider * @param _delegator - address of delegator */ function requestRemoveDelegator(address _serviceProvider, address _delegator) external { _requireIsInitialized(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] == 0, "DelegateManager: Pending remove delegator request" ); require( _delegatorExistsForSP(_delegator, _serviceProvider), ERROR_DELEGATOR_STAKE ); // Update lockup removeDelegatorRequests[_serviceProvider][_delegator] = ( block.number + removeDelegatorLockupDuration ); emit RemoveDelegatorRequested( _serviceProvider, _delegator, removeDelegatorRequests[_serviceProvider][_delegator] ); } /** * @notice Cancel pending removeDelegator request * @param _serviceProvider - address of service provider * @param _delegator - address of delegator */ function cancelRemoveDelegatorRequest(address _serviceProvider, address _delegator) external { require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] != 0, "DelegateManager: No pending request" ); // Reset lockup expiry removeDelegatorRequests[_serviceProvider][_delegator] = 0; emit RemoveDelegatorRequestCancelled(_serviceProvider, _delegator); } /** * @notice Evaluate removeDelegator request * @param _serviceProvider - address of service provider * @param _delegator - address of delegator * @return Updated total amount delegated to the service provider by delegator */ function removeDelegator(address _serviceProvider, address _delegator) external { _requireIsInitialized(); _requireStakingAddressIsSet(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] != 0, "DelegateManager: No pending request" ); // Enforce lockup expiry block require( block.number >= removeDelegatorRequests[_serviceProvider][_delegator], "DelegateManager: Lockup must be expired" ); // Enforce evaluation window for request require( block.number < removeDelegatorRequests[_serviceProvider][_delegator] + removeDelegatorEvalDuration, "DelegateManager: RemoveDelegator evaluation window expired" ); uint256 unstakeAmount = delegateInfo[_delegator][_serviceProvider]; // Unstake on behalf of target service provider Staking(stakingAddress).undelegateStakeFor( _serviceProvider, _delegator, unstakeAmount ); // Update total delegated for SP // totalServiceProviderDelegatedStake - total amount delegated to service provider // totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider _updateDelegatorStake( _delegator, _serviceProvider, spDelegateInfo[_serviceProvider].totalDelegatedStake.sub(unstakeAmount), delegateInfo[_delegator][_serviceProvider].sub(unstakeAmount), delegatorTotalStake[_delegator].sub(unstakeAmount) ); if ( _undelegateRequestIsPending(_delegator) && undelegateRequests[_delegator].serviceProvider == _serviceProvider ) { // Remove pending request information _updateServiceProviderLockupAmount( _serviceProvider, spDelegateInfo[_serviceProvider].totalLockedUpStake.sub(undelegateRequests[_delegator].amount) ); _resetUndelegateStakeRequest(_delegator); } // Remove from list of delegators _removeFromDelegatorsList(_serviceProvider, _delegator); // Reset lockup expiry removeDelegatorRequests[_serviceProvider][_delegator] = 0; emit RemoveDelegatorRequestEvaluated(_serviceProvider, _delegator, unstakeAmount); } /** * @notice SP can update their minDelegationAmount * @param _serviceProvider - address of service provider * @param _spMinDelegationAmount - new minDelegationAmount for SP * @notice does not enforce _spMinDelegationAmount >= minDelegationAmount since not necessary * delegateStake() and undelegateStake() always take the max of both already */ function updateSPMinDelegationAmount( address _serviceProvider, uint256 _spMinDelegationAmount ) external { _requireIsInitialized(); require(msg.sender == _serviceProvider, ERROR_ONLY_SERVICE_PROVIDER); /** * Ensure _serviceProvider is a valid SP * No objective source of truth, closest heuristic is numEndpoints > 0 */ (,,, uint256 numEndpoints,,) = ( ServiceProviderFactory(serviceProviderFactoryAddress) .getServiceProviderDetails(_serviceProvider) ); require(numEndpoints > 0, ERROR_ONLY_SERVICE_PROVIDER); spMinDelegationAmounts[_serviceProvider] = _spMinDelegationAmount; emit SPMinDelegationAmountUpdated(_serviceProvider, _spMinDelegationAmount); } /** * @notice Update duration for undelegate request lockup * @param _duration - new lockup duration */ function updateUndelegateLockupDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateUndelegateLockupDuration(_duration); emit UndelegateLockupDurationUpdated(_duration); } /** * @notice Update maximum delegators allowed * @param _maxDelegators - new max delegators */ function updateMaxDelegators(uint256 _maxDelegators) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); maxDelegators = _maxDelegators; emit MaxDelegatorsUpdated(_maxDelegators); } /** * @notice Update minimum delegation amount * @param _minDelegationAmount - min new min delegation amount */ function updateMinDelegationAmount(uint256 _minDelegationAmount) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); minDelegationAmount = _minDelegationAmount; emit MinDelegationUpdated(_minDelegationAmount); } /** * @notice Update remove delegator lockup duration * @param _duration - new lockup duration */ function updateRemoveDelegatorLockupDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateRemoveDelegatorLockupDuration(_duration); emit RemoveDelegatorLockupDurationUpdated(_duration); } /** * @notice Update remove delegator evaluation window duration * @param _duration - new window duration */ function updateRemoveDelegatorEvalDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); removeDelegatorEvalDuration = _duration; emit RemoveDelegatorEvalDurationUpdated(_duration); } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); governanceAddress = _governanceAddress; emit GovernanceAddressUpdated(_governanceAddress); } /** * @notice Set the Staking address * @dev Only callable by Governance address * @param _stakingAddress - address for new Staking contract */ function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _stakingAddress; emit StakingAddressUpdated(_stakingAddress); } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by Governance address * @param _spFactory - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _spFactory) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceProviderFactoryAddress = _spFactory; emit ServiceProviderFactoryAddressUpdated(_spFactory); } /** * @notice Set the ClaimsManager address * @dev Only callable by Governance address * @param _claimsManagerAddress - address for new ClaimsManager contract */ function setClaimsManagerAddress(address _claimsManagerAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); claimsManagerAddress = _claimsManagerAddress; emit ClaimsManagerAddressUpdated(_claimsManagerAddress); } // ========================================= View Functions ========================================= /** * @notice Get list of delegators for a given service provider * @param _sp - service provider address */ function getDelegatorsList(address _sp) external view returns (address[] memory) { _requireIsInitialized(); return spDelegateInfo[_sp].delegators; } /** * @notice Get total delegation from a given address * @param _delegator - delegator address */ function getTotalDelegatorStake(address _delegator) external view returns (uint256) { _requireIsInitialized(); return delegatorTotalStake[_delegator]; } /// @notice Get total amount delegated to a service provider function getTotalDelegatedToServiceProvider(address _sp) external view returns (uint256) { _requireIsInitialized(); return spDelegateInfo[_sp].totalDelegatedStake; } /// @notice Get total delegated stake locked up for a service provider function getTotalLockedDelegationForServiceProvider(address _sp) external view returns (uint256) { _requireIsInitialized(); return spDelegateInfo[_sp].totalLockedUpStake; } /// @notice Get total currently staked for a delegator, for a given service provider function getDelegatorStakeForServiceProvider(address _delegator, address _serviceProvider) external view returns (uint256) { _requireIsInitialized(); return delegateInfo[_delegator][_serviceProvider]; } /** * @notice Get status of pending undelegate request for a given address * @param _delegator - address of the delegator */ function getPendingUndelegateRequest(address _delegator) external view returns (address target, uint256 amount, uint256 lockupExpiryBlock) { _requireIsInitialized(); UndelegateStakeRequest memory req = undelegateRequests[_delegator]; return (req.serviceProvider, req.amount, req.lockupExpiryBlock); } /** * @notice Get status of pending remove delegator request for a given address * @param _serviceProvider - address of the service provider * @param _delegator - address of the delegator * @return - current lockup expiry block for remove delegator request */ function getPendingRemoveDelegatorRequest( address _serviceProvider, address _delegator ) external view returns (uint256) { _requireIsInitialized(); return removeDelegatorRequests[_serviceProvider][_delegator]; } /** * @notice Get minDelegationAmount for given SP * @param _serviceProvider - address of the service provider * @return - minDelegationAmount for given SP */ function getSPMinDelegationAmount(address _serviceProvider) external view returns (uint256) { return spMinDelegationAmounts[_serviceProvider]; } /// @notice Get current undelegate lockup duration function getUndelegateLockupDuration() external view returns (uint256) { _requireIsInitialized(); return undelegateLockupDuration; } /// @notice Current maximum delegators function getMaxDelegators() external view returns (uint256) { _requireIsInitialized(); return maxDelegators; } /// @notice Get minimum delegation amount function getMinDelegationAmount() external view returns (uint256) { _requireIsInitialized(); return minDelegationAmount; } /// @notice Get the duration for remove delegator request lockup function getRemoveDelegatorLockupDuration() external view returns (uint256) { _requireIsInitialized(); return removeDelegatorLockupDuration; } /// @notice Get the duration for evaluation of remove delegator operations function getRemoveDelegatorEvalDuration() external view returns (uint256) { _requireIsInitialized(); return removeDelegatorEvalDuration; } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the ClaimsManager address function getClaimsManagerAddress() external view returns (address) { _requireIsInitialized(); return claimsManagerAddress; } /// @notice Get the Staking address function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } // ========================================= Internal functions ========================================= /** * @notice Helper function for claimRewards to get balances from Staking contract and do validation * @param spFactory - reference to ServiceProviderFactory contract * @param _serviceProvider - address for which rewards are being claimed * @return (totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, spLockedStake, totalRewards, deployerCut) */ function _validateClaimRewards(ServiceProviderFactory spFactory, address _serviceProvider) internal returns ( uint256 totalBalanceInStaking, uint256 totalBalanceInSPFactory, uint256 totalActiveFunds, uint256 totalRewards, uint256 deployerCut ) { // Account for any pending locked up stake for the service provider (uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_serviceProvider); uint256 totalLockedUpStake = ( spDelegateInfo[_serviceProvider].totalLockedUpStake.add(spLockedStake) ); // Process claim for msg.sender // Total locked parameter is equal to delegate locked up stake + service provider locked up stake uint256 mintedRewards = ClaimsManager(claimsManagerAddress).processClaim( _serviceProvider, totalLockedUpStake ); // Amount stored in staking contract for owner totalBalanceInStaking = Staking(stakingAddress).totalStakedFor(_serviceProvider); // Amount in sp factory for claimer ( totalBalanceInSPFactory, deployerCut, ,,, ) = spFactory.getServiceProviderDetails(_serviceProvider); // Require active stake to claim any rewards // Amount in delegate manager staked to service provider uint256 totalBalanceOutsideStaking = ( totalBalanceInSPFactory.add(spDelegateInfo[_serviceProvider].totalDelegatedStake) ); totalActiveFunds = totalBalanceOutsideStaking.sub(totalLockedUpStake); require( mintedRewards == totalBalanceInStaking.sub(totalBalanceOutsideStaking), "DelegateManager: Reward amount mismatch" ); // Emit claim event emit Claim(_serviceProvider, totalRewards, totalBalanceInStaking); return ( totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, mintedRewards, deployerCut ); } /** * @notice Perform state updates when a delegate stake has changed * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @param _totalServiceProviderDelegatedStake - total delegated to this service provider * @param _totalStakedForSpFromDelegator - total delegated to this service provider by delegator * @param _totalDelegatorStake - total delegated from this delegator address */ function _updateDelegatorStake( address _delegator, address _serviceProvider, uint256 _totalServiceProviderDelegatedStake, uint256 _totalStakedForSpFromDelegator, uint256 _totalDelegatorStake ) internal { // Update total delegated for SP spDelegateInfo[_serviceProvider].totalDelegatedStake = _totalServiceProviderDelegatedStake; // Update amount staked from this delegator to targeted service provider delegateInfo[_delegator][_serviceProvider] = _totalStakedForSpFromDelegator; // Update total delegated from this delegator _updateDelegatorTotalStake(_delegator, _totalDelegatorStake); } /** * @notice Reset pending undelegate stake request * @param _delegator - address of delegator */ function _resetUndelegateStakeRequest(address _delegator) internal { _updateUndelegateStakeRequest(_delegator, address(0), 0, 0); } /** * @notice Perform updates when undelegate request state has changed * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @param _amount - amount being undelegated * @param _lockupExpiryBlock - block at which stake can be undelegated */ function _updateUndelegateStakeRequest( address _delegator, address _serviceProvider, uint256 _amount, uint256 _lockupExpiryBlock ) internal { // Update lockup information undelegateRequests[_delegator] = UndelegateStakeRequest({ lockupExpiryBlock: _lockupExpiryBlock, amount: _amount, serviceProvider: _serviceProvider }); } /** * @notice Update total amount delegated from an address * @param _delegator - address of service provider * @param _amount - updated delegator total */ function _updateDelegatorTotalStake(address _delegator, uint256 _amount) internal { delegatorTotalStake[_delegator] = _amount; } /** * @notice Update amount currently locked up for this service provider * @param _serviceProvider - address of service provider * @param _updatedLockupAmount - updated lock up amount */ function _updateServiceProviderLockupAmount( address _serviceProvider, uint256 _updatedLockupAmount ) internal { spDelegateInfo[_serviceProvider].totalLockedUpStake = _updatedLockupAmount; } function _removeFromDelegatorsList(address _serviceProvider, address _delegator) internal { for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) { if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) { // Overwrite and shrink delegators list spDelegateInfo[_serviceProvider].delegators[i] = spDelegateInfo[_serviceProvider].delegators[spDelegateInfo[_serviceProvider].delegators.length - 1]; spDelegateInfo[_serviceProvider].delegators.length--; break; } } } /** * @notice Helper function to distribute rewards to any delegators * @param _sp - service provider account tracked in staking * @param _totalActiveFunds - total funds minus any locked stake * @param _totalRewards - total rewaards generated in this round * @param _deployerCut - service provider cut of delegate rewards, defined as deployerCut / deployerCutBase * @param _deployerCutBase - denominator value for calculating service provider cut as a % * @return (totalBalanceInStaking, totalBalanceInSPFactory, totalBalanceOutsideStaking) */ function _distributeDelegateRewards( address _sp, uint256 _totalActiveFunds, uint256 _totalRewards, uint256 _deployerCut, uint256 _deployerCutBase ) internal returns (uint256 totalDelegatedStakeIncrease) { // Traverse all delegates and calculate their rewards // As each delegate reward is calculated, increment SP cut reward accordingly for (uint256 i = 0; i < spDelegateInfo[_sp].delegators.length; i++) { address delegator = spDelegateInfo[_sp].delegators[i]; uint256 delegateStakeToSP = delegateInfo[delegator][_sp]; // Subtract any locked up stake if (undelegateRequests[delegator].serviceProvider == _sp) { delegateStakeToSP = delegateStakeToSP.sub(undelegateRequests[delegator].amount); } // Calculate rewards by ((delegateStakeToSP / totalActiveFunds) * totalRewards) uint256 rewardsPriorToSPCut = ( delegateStakeToSP.mul(_totalRewards) ).div(_totalActiveFunds); // Multiply by deployer cut fraction to calculate reward for SP // Operation constructed to perform all multiplication prior to division // uint256 spDeployerCut = (rewardsPriorToSPCut * deployerCut ) / (deployerCutBase); // = ((delegateStakeToSP * totalRewards) / totalActiveFunds) * deployerCut ) / (deployerCutBase); // = ((delegateStakeToSP * totalRewards * deployerCut) / totalActiveFunds ) / (deployerCutBase); // = (delegateStakeToSP * totalRewards * deployerCut) / (deployerCutBase * totalActiveFunds); uint256 spDeployerCut = ( (delegateStakeToSP.mul(_totalRewards)).mul(_deployerCut) ).div( _totalActiveFunds.mul(_deployerCutBase) ); // Increase total delegate reward in DelegateManager // Subtract SP reward from rewards to calculate delegate reward // delegateReward = rewardsPriorToSPCut - spDeployerCut; delegateInfo[delegator][_sp] = ( delegateInfo[delegator][_sp].add(rewardsPriorToSPCut.sub(spDeployerCut)) ); // Update total for this delegator _updateDelegatorTotalStake( delegator, delegatorTotalStake[delegator].add(rewardsPriorToSPCut.sub(spDeployerCut)) ); totalDelegatedStakeIncrease = ( totalDelegatedStakeIncrease.add(rewardsPriorToSPCut.sub(spDeployerCut)) ); } return (totalDelegatedStakeIncrease); } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "DelegateManager: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } /** * @notice Set the remove delegator lockup duration after validating against governance * @param _duration - Incoming remove delegator duration value */ function _updateRemoveDelegatorLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "DelegateManager: removeDelegatorLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); removeDelegatorLockupDuration = _duration; } /** * @notice Set the undelegate lockup duration after validating against governance * @param _duration - Incoming undelegate lockup duration value */ function _updateUndelegateLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "DelegateManager: undelegateLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); undelegateLockupDuration = _duration; } /** * @notice Returns if delegator has delegated to a service provider * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @return boolean indicating whether delegator exists for service provider */ function _delegatorExistsForSP( address _delegator, address _serviceProvider ) internal view returns (bool) { for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) { if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) { return true; } } // Not found return false; } /** * @notice Determine if a claim is pending for this service provider * @param _sp - address of service provider * @return boolean indicating whether a claim is pending */ function _claimPending(address _sp) internal view returns (bool) { ClaimsManager claimsManager = ClaimsManager(claimsManagerAddress); return claimsManager.claimPending(_sp); } /** * @notice Determine if a decrease request has been initiated * @param _delegator - address of delegator * @return boolean indicating whether a decrease request is pending */ function _undelegateRequestIsPending(address _delegator) internal view returns (bool) { return ( (undelegateRequests[_delegator].lockupExpiryBlock != 0) && (undelegateRequests[_delegator].amount != 0) && (undelegateRequests[_delegator].serviceProvider != address(0)) ); } // ========================================= Private Functions ========================================= function _requireStakingAddressIsSet() private view { require( stakingAddress != address(0x00), "DelegateManager: stakingAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "DelegateManager: serviceProviderFactoryAddress is not set" ); } function _requireClaimsManagerAddressIsSet() private view { require( claimsManagerAddress != address(0x00), "DelegateManager: claimsManagerAddress is not set" ); } }
Submit request for undelegation _target - address of service provider to undelegate stake from _amount - amount in wei to undelegate return Updated total amount delegated to the service provider by delegator/ Confirm no pending delegation request Ensure valid bounds Submit updated request for sender, with target sp, undelegate amount, target expiry block Update total locked for this service provider, increasing by unstake amount
function requestUndelegateStake( address _target, uint256 _amount ) external returns (uint256) { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( _amount > 0, "DelegateManager: Requested undelegate stake amount must be greater than zero" ); require( !_claimPending(_target), "DelegateManager: Undelegate request not permitted for SP pending claim" ); address delegator = msg.sender; require( _delegatorExistsForSP(delegator, _target), ERROR_DELEGATOR_STAKE ); require( !_undelegateRequestIsPending(delegator), "DelegateManager: No pending lockup expected" ); uint256 currentlyDelegatedToSP = delegateInfo[delegator][_target]; require( _amount <= currentlyDelegatedToSP, "DelegateManager: Cannot decrease greater than currently staked for this ServiceProvider" ); uint256 lockupExpiryBlock = block.number.add(undelegateLockupDuration); _updateUndelegateStakeRequest( delegator, _target, _amount, lockupExpiryBlock ); _updateServiceProviderLockupAmount( _target, spDelegateInfo[_target].totalLockedUpStake.add(_amount) ); emit UndelegateStakeRequested(delegator, _target, _amount, lockupExpiryBlock); return delegateInfo[delegator][_target].sub(_amount); }
1,231,938
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "hardhat/console.sol"; import "./interfaces/IMultiRewards.sol"; import "./interfaces/IAngle.sol"; interface IController { function withdraw(address, uint256) external; function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); function strategies(address) external view returns (address); } interface IStrategy { function stake() external; } contract Vault is ERC20 { using SafeERC20 for IERC20; using Address for address; IERC20 public token; address public sanUSDC_EUR = 0x9C215206Da4bf108aE5aEEf9dA7caD3352A36Dad; address public staking = 0x2Fa1255383364F6e17Be6A6aC7A56C9aCD6850a3; address public stableMaster = 0x5adDc89785D75C86aB939E9e15bfBBb7Fc086A87; address public poolManager = 0xe9f183FC656656f1F17af1F2b0dF79b8fF9ad8eD; address public governance; address public controller; address public gauge; constructor(address _token, address _controller) ERC20("Stake DAO Angle USDC strat", "sdsanUSDC_EUR") { token = IERC20(_token); governance = msg.sender; controller = _controller; } function deposit(uint256 _amount) public { require(gauge != address(0), "Gauge not yet initialized"); token.safeTransferFrom(msg.sender, address(this), _amount); // rate 1:1 with san LP minted uint256 shares = _earn(); _mint(address(this), shares); IERC20(address(this)).approve(gauge, shares); IMultiRewards(gauge).stakeFor(msg.sender, shares); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function _earn() internal returns (uint256) { uint256 _bal = token.balanceOf(address(this)); uint256 stakedBefore = IERC20(sanUSDC_EUR).balanceOf(address(this)); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); uint256 stakedAfter = IERC20(sanUSDC_EUR).balanceOf(address(this)); return stakedAfter - stakedBefore; } function withdraw(uint256 _shares) public { uint256 userTotalShares = IMultiRewards(gauge).balanceOf(msg.sender); require(_shares <= userTotalShares, "Not enough staked"); IMultiRewards(gauge).withdrawFor(msg.sender, _shares); _burn(address(this), _shares); uint256 sanUsdcEurBal = IERC20(sanUSDC_EUR).balanceOf(address(this)); if (_shares > sanUsdcEurBal) { IController(controller).withdraw(address(token), _shares); } else { IStableMaster(stableMaster).withdraw(_shares, address(this), address(this), IPoolManager(poolManager)); } uint256 usdcAmount = IERC20(token).balanceOf(address(this)); token.safeTransfer(msg.sender, usdcAmount); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } function getPricePerFullShare() public pure returns (uint256) { return 1e6; } function balance() public view returns (uint256) { return IController(controller).balanceOf(address(token)); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) public { require(msg.sender == governance, "!governance"); controller = _controller; } function setGauge(address _gauge) public { require(msg.sender == governance, "!governance"); gauge = _gauge; } function decimals() public view override returns (uint8) { return 6; } function earn() external { require(msg.sender == governance, "!governance"); address strategy = IController(controller).strategies(address(token)); uint256 _bal = IERC20(sanUSDC_EUR).balanceOf(address(this)); IERC20(sanUSDC_EUR).safeTransfer(strategy, _bal); IStrategy(strategy).stake(); } function withdrawRescue() external { uint256 userTotalShares = IMultiRewards(gauge).balanceOf(msg.sender); IMultiRewards(gauge).withdrawFor(msg.sender, userTotalShares); _burn(address(this), userTotalShares); IERC20(sanUSDC_EUR).transfer(msg.sender, userTotalShares); } } // SPDX-License-Identifier: GNU GPLv3 pragma solidity >=0.8.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // ====================================== IAngle.sol =============================== // This file contains the interfaces for the main contracts of Angle protocol. // Some of these contracts need to be deployed several times across the protocol with different // initializations. We only leave in the following interfaces the user-facing functions // that anyone can call without having a role. There are some view functions and some // state-changing functions. /// @notice Interface for the `PoolManager` contract handling the collateral of the protocol /// @dev There is one such contract per stablecoin/collateral pair interface IPoolManager { /// @return apr Estimated Annual Percentage Rate for SLPs based on lending to other protocols function estimatedAPR() external view returns (uint256 apr); /// @return The amount of the underlying collateral that the contract currently owns function getBalance() external view returns (uint256); /// @return The amount of collateral owned by this contract plus the amount that has been lent to strategies function getTotalAsset() external view returns (uint256); } /// @notice Interface for `StableMaster`, the contract handling all the collateral types accepted for a given stablecoin interface IStableMaster { // Struct to handle all the parameters to manage the fees // related to a given collateral pool (associated to the stablecoin) struct MintBurnData { // Values of the thresholds to compute the minting fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeMint; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeMint; // Values of the thresholds to compute the burning fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeBurn; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeBurn; // Max proportion of collateral from users that can be covered by HAs // It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated // the other changes accordingly uint64 targetHAHedge; // Minting fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusMint; // Burning fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusBurn; // Parameter used to limit the number of stablecoins that can be issued using the concerned collateral uint256 capOnStableMinted; } // Struct to handle all the variables and parameters to handle SLPs in the protocol // including the fraction of interests they receive or the fees to be distributed to // them struct SLPData { // Last timestamp at which the `sanRate` has been updated for SLPs uint256 lastBlockUpdated; // Fees accumulated from previous blocks and to be distributed to SLPs uint256 lockedInterests; // Max interests used to update the `sanRate` in a single block // Should be in collateral token base uint256 maxInterestsDistributed; // Amount of fees left aside for SLPs and that will be distributed // when the protocol is collateralized back again uint256 feesAside; // Part of the fees normally going to SLPs that is left aside // before the protocol is collateralized back again (depends on collateral ratio) // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippageFee; // Portion of the fees from users minting and burning // that goes to SLPs (the rest goes to surplus) uint64 feesForSLPs; // Slippage factor that's applied to SLPs exiting (depends on collateral ratio) // If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippage; // Portion of the interests from lending // that goes to SLPs (the rest goes to surplus) uint64 interestsForSLPs; } struct Collateral { // Interface for the token accepted by the underlying `PoolManager` contract IERC20 token; // Reference to the `SanToken` for the pool ISanToken sanToken; // Reference to the `PerpetualManager` for the pool IPerpetualManager perpetualManager; // Adress of the oracle for the change rate between // collateral and the corresponding stablecoin IOracle oracle; // Amount of collateral in the reserves that comes from users // converted in stablecoin value. Updated at minting and burning. // A `stocksUsers` of 10 for a collateral type means that overall the balance of the collateral from users // that minted/burnt stablecoins using this collateral is worth 10 of stablecoins uint256 stocksUsers; // Exchange rate between sanToken and collateral uint256 sanRate; // Base used in the collateral implementation (ERC20 decimal) uint256 collatBase; // Parameters for SLPs and update of the `sanRate` SLPData slpData; // All the fees parameters MintBurnData feeData; } /// @notice Lets a user send collateral to the system to mint stablecoins /// @param amount Amount of collateral sent /// @param user Address of the contract or the person to give the minted tokens to /// @param poolManager Address of the `PoolManager` of the required collateral /// @param minStableAmount Minimum amount of stablecoins the user wants to get with this transaction /// @dev The `poolManager` refers to the collateral that the user wants to send /// @dev `minStableAmount` serves as a slippage protection for users function mint( uint256 amount, address user, IPoolManager poolManager, uint256 minStableAmount ) external; /// @notice Lets a user burn agTokens (stablecoins) and receive the collateral specified by the `poolManager` /// in exchange /// @param amount Amount of stable asset burnt /// @param burner Address from which the agTokens will be burnt /// @param dest Address where collateral is going to be sent /// @param poolManager Collateral type requested by the user burning /// @param minCollatAmount Minimum amount of collateral that the user wants to get with this transaction function burn( uint256 amount, address burner, address dest, IPoolManager poolManager, uint256 minCollatAmount ) external; /// @notice Lets a SLP enter the protocol by sending collateral to the system in exchange of sanTokens /// @param user Address of the SLP to send sanTokens to /// @param amount Amount of collateral sent /// @param poolManager Address of the `PoolManager` of the required collateral: the corresponding collateral /// type is the one that is going to be sent by the user function deposit( uint256 amount, address user, IPoolManager poolManager ) external; /// @notice Lets a SLP burn of sanTokens and receive the corresponding collateral back in exchange at the /// current exchange rate between sanTokens and collateral /// @param amount Amount of sanTokens burnt by the SLP /// @param burner Address that will burn its sanTokens /// @param dest Address that will receive the collateral /// @param poolManager Address of the `PoolManager` of the required collateral function withdraw( uint256 amount, address burner, address dest, IPoolManager poolManager ) external; /// @return Collateral ratio for this stablecoin function getCollateralRatio() external view returns (uint256); function collateralMap(IPoolManager poolManager) external view returns ( IERC20 token, ISanToken sanToken, IPerpetualManager perpetualManager, IOracle oracle, uint256 stocksUsers, uint256 sanRate, uint256 collatBase, SLPData memory slpData, MintBurnData memory feeData ); } /// @notice Interface for the contract managing perpetuals: there is one such contract per collateral/stablecoin /// pair in the protocol interface IPerpetualManager { /// @notice Lets a HA join the protocol and create a perpetual /// @param owner Address of the future owner of the perpetual /// @param margin Amount of collateral brought by the HA /// @param committedAmount Amount of collateral hedged by the HA /// @param maxOracleRate Maximum oracle value that the HA wants to see stored in the perpetual /// @param minNetMargin Minimum net margin that the HA is willing to see stored in the perpetual /// @return perpetualID The ID of the perpetual opened by this HA /// @dev The future owner of the perpetual cannot be the zero address /// @dev It is possible to open a perpetual on behalf of someone else /// @dev The `maxOracleRate` parameter serves as a protection against oracle manipulations for HAs opening perpetuals /// @dev `minNetMargin` is a protection against too big variations in the fees for HAs function openPerpetual( address owner, uint256 margin, uint256 committedAmount, uint256 maxOracleRate, uint256 minNetMargin ) external returns (uint256 perpetualID); /// @notice Lets a HA close a perpetual owned or controlled for the stablecoin/collateral pair associated /// to this `PerpetualManager` contract /// @param perpetualID ID of the perpetual to close /// @param to Address which will receive the proceeds from this perpetual /// @param minCashOutAmount Minimum net cash out amount that the HA is willing to get for closing the /// perpetual /// @dev The HA gets the current amount of her position depending on the entry oracle value /// and current oracle value minus some transaction fees computed on the committed amount /// @dev `msg.sender` should be the owner of `perpetualID` or be approved for this perpetual /// @dev If the `PoolManager` does not have enough collateral, the perpetual owner will be converted to a SLP and /// receive sanTokens /// @dev The `minCashOutAmount` serves as a protection for HAs closing their perpetuals: it protects them both /// from fees that would have become too high and from a too big decrease in oracle value function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external; /// @notice Lets a HA increase the `margin` in a perpetual she controls for this /// stablecoin/collateral pair /// @param perpetualID ID of the perpetual to which amount should be added to `margin` /// @param amount Amount to add to the perpetual's `margin` function addToPerpetual(uint256 perpetualID, uint256 amount) external; /// @notice Lets a HA decrease the `margin` in a perpetual she controls for this /// stablecoin/collateral pair /// @param perpetualID ID of the perpetual from which collateral should be removed /// @param amount Amount to remove from the perpetual's `margin` /// @param to Address which will receive the collateral removed from this perpetual function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external; // =========================== External View Function ========================== /// @notice Returns the `cashOutAmount` of the perpetual owned by someone at a given oracle value /// @param perpetualID ID of the perpetual /// @param rate Oracle value /// @return The `cashOutAmount` of the perpetual /// @return Whether the position of the perpetual is now too small compared with its initial position function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256); // =========================== Reward Distribution ============================= /// @notice Allows to check the amount of reward tokens earned by a perpetual /// @param perpetualID ID of the perpetual to check /// @return The earned tokens by the perpetual that have not been claimed yet function earned(uint256 perpetualID) external view returns (uint256); /// @notice Allows a perpetual owner to withdraw rewards /// @param perpetualID ID of the perpetual which accumulated tokens /// @dev Only an approved caller can claim the rewards for the perpetual with perpetualID function getReward(uint256 perpetualID) external; // =============================== ERC721 logic ================================ /// @notice Gets the balance of an owner /// @param owner Address of the owner /// @return Balance (ie the number of perpetuals) owned by a HA function balanceOf(address owner) external view returns (uint256); /// @notice Gets the owner of the perpetual with ID perpetualID /// @param perpetualID ID of the perpetual /// @return Owner address function ownerOf(uint256 perpetualID) external view returns (address); /// @notice Approves to an address specified by `to` a perpetual specified by `perpetualID` /// @param to Address to approve the perpetual to /// @param perpetualID ID of the perpetual function approve(address to, uint256 perpetualID) external; /// @param perpetualID ID of the concerned perpetual /// @return Approved address by a perpetual owner function getApproved(uint256 perpetualID) external view returns (address); /// @notice Sets approval on all perpetuals owned by the owner to an operator /// @param operator Address to approve (or block) on all perpetuals /// @param approved Whether the sender wants to approve or block the operator function setApprovalForAll(address operator, bool approved) external; /// @param owner Owner of perpetuals /// @param operator Address to check if approved /// @return If the operator address is approved on all perpetuals by the owner function isApprovedForAll(address owner, address operator) external view returns (bool); /// @param perpetualID ID of the perpetual /// @return If the sender address is approved for the perpetualId function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool); /// @notice Transfers the `perpetualID` from an address to another /// @param from Source address /// @param to Destination a address /// @param perpetualID ID of the perpetual to transfer function transferFrom( address from, address to, uint256 perpetualID ) external; /// @notice Safely transfers the `perpetualID` from an address to another without data in it /// @param from Source address /// @param to Destination a address /// @param perpetualID ID of the perpetual to transfer function safeTransferFrom( address from, address to, uint256 perpetualID ) external; /// @notice Safely transfers the `perpetualID` from an address to another with data in the transfer /// @param from Source address /// @param to Destination a address /// @param perpetualID ID of the perpetual to transfer function safeTransferFrom( address from, address to, uint256 perpetualID, bytes memory _data ) external; } /// @notice Interface for the staking contract of the Angle protocol interface IStakingRewards { /// @dev Used instead of having a public variable to respect the ERC20 standard /// @return Total supply function totalSupply() external view returns (uint256); /// @param account Account to query the balance of /// @return Number of token staked by an account function balanceOf(address account) external view returns (uint256); /// @return Current timestamp if a reward is being distributed and the end of the staking /// period if staking is done function lastTimeRewardApplicable() external view returns (uint256); /// @notice Returns how much unclaimed rewards an account has /// @param account Address for which the request is made /// @return How much a given account earned rewards function earned(address account) external view returns (uint256); /// @notice Lets someone stake a given amount of `stakingTokens` /// @param amount Amount of ERC20 staking token that the `msg.sender` wants to stake function stake(uint256 amount) external; /// @notice Allows to stake on behalf of another address /// @param amount Amount to stake /// @param onBehalf Address to stake onBehalf of function stakeOnBehalf(uint256 amount, address onBehalf) external; /// @notice Lets a user withdraw a given amount of collateral from the staking contract /// @param amount Amount of the ERC20 staking token that the `msg.sender` wants to withdraw function withdraw(uint256 amount) external; /// @notice Triggers a payment of the reward earned to the msg.sender function getReward() external; /// @notice Lets the caller withdraw its staking and claim rewards function exit() external; } /// @notice Interface for agToken, that is to say Angle's stablecoins /// @dev This contract is used to create and handle the stablecoins of Angle protocol /// @dev Only the `StableMaster` contract can mint or burn agTokens /// @dev It is still possible for any address to burn its agTokens without redeeming collateral in exchange /// @dev agTokens are classical ERC-20 tokens, so it is still possible to `approve` an address, `transfer` or /// `transferFrom` the tokens interface IAgToken { /// @notice Burns `amount` of agToken on behalf of another account without redeeming collateral back /// @param account Account to burn on behalf of /// @param amount Amount to burn /// @param poolManager Reference to the `PoolManager` contract for which the `stocksUsers` will /// need to be updated /// @dev When calling this function, people should specify the `poolManager` for which they want to decrease /// the `stocksUsers`: this a way for the protocol to maintain healthy accounting variables /// @dev This function is for instance to be used by governance to burn the tokens accumulated by the `BondingCurve` /// contract function burnFromNoRedeem( address account, uint256 amount, address poolManager ) external; /// @notice Destroys `amount` token from the caller without giving collateral back /// @param amount Amount to burn /// @param poolManager Reference to the `PoolManager` contract for which the `stocksUsers` will need to be updated function burnNoRedeem(uint256 amount, address poolManager) external; } /// @notice Interface for sanTokens, these tokens are used to mark the debt the contract has to SLPs /// @dev The exchange rate between sanTokens and collateral will automatically change as interests and transaction fees accrue to SLPs /// @dev There is one `SanToken` contract per pair stablecoin/collateral /// @dev Only the `StableMaster` contract can mint or burn sanTokens /// @dev It is still possible for any address to burn its sanTokens without redeeming collateral in exchange /// @dev Like `AgTokens`, sanTokens are classical ERC-20 tokens, so it is still possible to `approve` an address, `transfer` or /// `transferFrom` the tokens interface ISanToken { /// @notice Destroys `amount` token for the caller without giving collateral back /// @param amount Amount to burn function burnNoRedeem(uint256 amount) external; } /// @notice Interface for the `Core` contract interface ICore { /// @return `_governorList` List of all the governor addresses of the protocol function governorList() external view returns (address[] memory); } /// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink, /// from just UniswapV3 or from just Chainlink interface IOracle { /// @notice Reads one of the rates from the circuits given /// @return rate The current rate between the in-currency and out-currency /// @dev By default if the oracle involves a Uniswap price and a Chainlink price /// this function will return the Uniswap price /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency) function read() external view returns (uint256 rate); /// @notice Read rates from the circuit of both Uniswap and Chainlink if there are both circuits /// else returns twice the same price /// @return Return all available rates (Chainlink and Uniswap) with the lowest rate returned first. /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency) function readAll() external view returns (uint256, uint256); /// @notice Reads rates from the circuit of both Uniswap and Chainlink if there are both circuits /// and returns either the highest of both rates or the lowest /// @return rate The lower rate between Chainlink and Uniswap /// @dev If there is only one rate computed in an oracle contract, then the only rate is returned /// regardless of the value of the `lower` parameter /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency) function readLower() external view returns (uint256 rate); /// @notice Reads rates from the circuit of both Uniswap and Chainlink if there are both circuits /// and returns either the highest of both rates or the lowest /// @return rate The upper rate between Chainlink and Uniswap /// @dev If there is only one rate computed in an oracle contract, then the only rate is returned /// regardless of the value of the `lower` parameter /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency) function readUpper() external view returns (uint256 rate); /// @notice Converts an in-currency quote amount to out-currency using one of the rates available in the oracle /// contract /// @param quoteAmount Amount (in the input collateral) to be converted to be converted in out-currency /// @return Quote amount in out-currency from the base amount in in-currency /// @dev Like in the read function, if the oracle involves a Uniswap and a Chainlink price, this function /// will use the Uniswap price to compute the out quoteAmount /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency) function readQuote(uint256 quoteAmount) external view returns (uint256); /// @notice Returns the lowest quote amount between Uniswap and Chainlink circuits (if possible). If the oracle /// contract only involves a single feed, then this returns the value of this feed /// @param quoteAmount Amount (in the input collateral) to be converted /// @return The lowest quote amount from the quote amount in in-currency /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency) function readQuoteLower(uint256 quoteAmount) external view returns (uint256); } /// @notice Interface for the `BondingCurve` contract /// @dev This contract allows people to buy ANGLE governance tokens using the protocol's stablecoins /// @dev It is with high certainty not going to be distributed directly at launch interface IBondingCurve { /// @notice Lets `msg.sender` buy tokens (ANGLE tokens normally) against an allowed token (a stablecoin normally) /// @param _agToken Reference to the agToken used, that is the stablecoin used to buy the token associated to this /// bonding curve /// @param maxAmountToPayInAgToken Maximum amount to pay in agTokens that the user is willing to pay to buy the /// `targetSoldTokenQuantity` function buySoldToken( IAgToken _agToken, uint256 targetSoldTokenQuantity, uint256 maxAmountToPayInAgToken ) external; /// @dev More generally than the expression used, the value of the price is: /// `startPrice/(1-tokensSoldInTx/tokensToSellInTotal)^power` with `power = 2` /// @dev The precision of this function is not that important as it is a view function anyone can query /// @notice Returns the current price of the token (expressed in reference) function getCurrentPrice() external view returns (uint256); /// @return The quantity of governance tokens that are still to be sold function getQuantityLeftToSell() external view returns (uint256); /// @param targetQuantity Quantity of ANGLE tokens to buy /// @dev This is an utility function that can be queried before buying tokens /// @return The amount to pay for the desired amount of ANGLE to buy function computePriceFromQuantity(uint256 targetQuantity) external view returns (uint256); } /// @title ICollateralSettler /// @notice Interface for the collateral settlement contracts that are used when a collateral is getting revoked interface ICollateralSettler { /// @notice Allows a user to claim collateral for a `dest` address by sending agTokens and gov tokens (optional) /// @param dest Address of the user to claim collateral for /// @param amountAgToken Amount of agTokens sent /// @param amountGovToken Amount of governance sent /// @dev The more gov tokens a user sends, the more preferably it ends up being treated during the redeem period function claimUser( address dest, uint256 amountAgToken, uint256 amountGovToken ) external; /// @notice Allows a HA to claim collateral by sending a `perpetualID` and gov tokens (optional) /// @param perpetualID Perpetual owned by the HA /// @param amountGovToken Amount of governance sent /// @dev The contract automatically recognizes the beneficiary of the perpetual function claimHA(uint256 perpetualID, uint256 amountGovToken) external; /// @notice Allows a SLP to claim collateral for an address `dest` by sending sanTokens and gov tokens (optional) /// @param dest Address to claim collateral for /// @param amountSanToken Amount of sanTokens sent /// @param amountGovToken Amount of governance tokens sent function claimSLP( address dest, uint256 amountSanToken, uint256 amountGovToken ) external; /// @notice Computes the base amount each category of claim will get after the claim period has ended /// @dev This function can only be called once when claim period is over /// @dev It is at the level of this function that the waterfall between the different /// categories of stakeholders and of claims is executed function setAmountToRedistributeEach() external; /// @notice Lets a user or a LP redeem its corresponding share of collateral /// @param user Address of the user to redeem collateral to /// @dev This function can only be called after the `setAmountToRedistributeEach` function has been called /// @dev The entry point to redeem is the same for users, HAs and SLPs function redeemCollateral(address user) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; interface IMultiRewards { function balanceOf(address) external returns(uint); function stakeFor(address, uint) external; function withdrawFor(address, uint) external; function notifyRewardAmount(address, uint) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } }
Burns `amount` of agToken on behalf of another account without redeeming collateral back account Account to burn on behalf of amount Amount to burn poolManager Reference to the `PoolManager` contract for which the `stocksUsers` will need to be updated When calling this function, people should specify the `poolManager` for which they want to decrease the `stocksUsers`: this a way for the protocol to maintain healthy accounting variables This function is for instance to be used by governance to burn the tokens accumulated by the `BondingCurve` contract Destroys `amount` token from the caller without giving collateral back amount Amount to burn poolManager Reference to the `PoolManager` contract for which the `stocksUsers` will need to be updated Interface for sanTokens, these tokens are used to mark the debt the contract has to SLPs The exchange rate between sanTokens and collateral will automatically change as interests and transaction fees accrue to SLPs There is one `SanToken` contract per pair stablecoin/collateral Only the `StableMaster` contract can mint or burn sanTokens It is still possible for any address to burn its sanTokens without redeeming collateral in exchange Like `AgTokens`, sanTokens are classical ERC-20 tokens, so it is still possible to `approve` an address, `transfer` or `transferFrom` the tokens
interface ISanToken { function burnNoRedeem(uint256 amount) external; }
1,288,373
pragma ton-solidity >= 0.38.2; /// @title LiquiSOR\DEXPool /// @author laugan /// @notice Contract for providing liquidity and trading. In the same time it's a root contract for TIP-3 Liquidity token pragma AbiHeader time; pragma AbiHeader expire; pragma AbiHeader pubkey; import "../std/lib/TVM.sol"; import "../tip3/int/ITIP3Root.sol"; import "../tip3/int/ITIP3Wallet.sol"; import "../dex/int/IDEXPool.sol"; import "../dex/lib/DEX.sol"; import "../dex/TIP3LiquidityWallet.sol"; contract DEXPool is IDEXPool, ITIP3RootMetadata, ITIP3WalletNotifyHandler, ITIP3WalletBurnHandler { /* * Attributes */ // Static address static dex_; // our owner bytes static name_; bytes static symbol_; TvmCell static code_; address static tokenX_; address static tokenY_; uint8 constant decimals_ = 12; uint128 constant fee_ = 300; // real order gets virtual fee, not this one uint64 constant DEX_VALUE_FEE = 0.005 ton; uint64 constant DEPLOY_FEE = 1.5 ton; uint64 constant USAGE_FEE = 0.2 ton; uint64 constant MESSAGE_FEE = 0.05 ton; uint64 constant CALLBACK_FEE = 0.01 ton; uint128 constant INITIAL_GAS = 0.5 ton; address constant ZERO_ADDRESS = address.makeAddrStd(0, 0); uint64 constant INIT_FEE = 3 ton; //USAGE_FEE + 3 * DEPLOY_FEE + 2 * MESSAGE_FEE + 2 * CALLBACK_FEE; uint64 constant CUSTOMER_FEE = 0.8 ton; //USAGE_FEE + 3 * MESSAGE_FEE + 2 * CALLBACK_FEE; uint128 constant MIN_TOKEN_AMOUNT = 1000; uint16 constant ERROR_ADDITION_OVERFLOW = 300; uint16 constant ERROR_SUBTRACTION_OVERFLOW = 301; uint16 constant ERROR_MULTIPLY_OVERFLOW = 302; Token detailsX_; Token detailsY_; uint128 total_supply_; mapping(uint256 => Transaction) transactions_; /// @dev Contract constructor. constructor(ITIP3RootMetadata.TokenDetails valueX, ITIP3RootMetadata.TokenDetails valueY) public { detailsX_.root = tokenX_; detailsY_.root = tokenY_; detailsX_.code = valueX.code; detailsY_.code = valueY.code; detailsX_.name = valueX.name; detailsY_.name = valueY.name; detailsX_.symbol = valueX.symbol; detailsY_.symbol = valueY.symbol; detailsX_.decimals = valueX.decimals; detailsY_.decimals = valueY.decimals; _deployWallets(); } /* ---------------------------------------------------------------------------------- */ /* TIP3 Metadata Functions */ function getTokenInfo() override external view returns (TokenDetails) { return ITIP3RootMetadata.TokenDetails(name_, symbol_, decimals_, code_, total_supply_, total_supply_); } function callTokenInfo() override external responsible view returns (TokenDetails) { return {value: 0, flag: TVM.FLAG_VALUE_ADD_INBOUND }ITIP3RootMetadata.TokenDetails(name_, symbol_, decimals_, code_, total_supply_, total_supply_); } /// @notice Calculates wallet address with defined public key (getter) function getWalletAddress(int8 workchainId, uint256 walletPubkey, address walletOwner) override external view returns (address) { return _expectedAddress(address(this), walletPubkey, walletOwner); } /// @notice Calculates wallet address with defined public key (responsible) function callWalletAddress(int8 workchainId, uint256 walletPubkey, address walletOwner) override external responsible view returns (address) { return {value: 0, flag: TVM.FLAG_VALUE_ADD_INBOUND}(_expectedAddress(address(this), walletPubkey, walletOwner)); } /* ---------------------------------------------------------------------------------- */ /* TIP3 Fungible Functions */ function deployEmptyWallet(int8 workchainId, uint256 walletPubkey, address walletOwner, uint128 grams) external returns (address walletAddress, TvmCell walletCode) { tvm.accept(); walletAddress = new TIP3LiquidityWallet{ value: grams, pubkey: walletPubkey, varInit: { //root_public_key_: 0, root_address_: address(this), wallet_public_key_: walletPubkey, wallet_owner_address_: walletOwner, name_: name_, symbol_: symbol_, decimals_: decimals_, code_: code_ }, wid: workchainId, code: code_ }(); walletCode = code_; } /* ---------------------------------------------------------------------------------- */ /* Pool Getters */ function getPoolDetails() external override view returns (PoolDetails details) { details = PoolDetails( detailsX_.root, detailsX_.wallet, detailsX_.balance, detailsY_.root, detailsY_.wallet, detailsY_.balance, fee_, total_supply_ ); } function getSwapDetails(address _tokenAddress, uint128 _tokens) external override view returns (OrderDetails) { (Token inToken, Token outToken, ) = _processToken(_tokenAddress); // does checks and fills variables with token details (uint128 spotPrice, uint128 effectivePrice) = (inToken.balance == 0 || outToken.balance == 0) ? (0,0) : ( _spotAmount(_tokens,inToken.balance, outToken.balance), _effectiveAmount(_tokens, inToken.balance, outToken.balance, fee_) ); return OrderDetails(spotPrice, effectivePrice); } function getDepositDetails(address _tokenAddress, uint128 _tokens) external override view returns (OrderDetails) { (Token inToken, Token outToken, ) = _processToken(_tokenAddress); // does checks and fills variables with token details (uint128 secondAmount, uint128 liqAmount) = (inToken.balance == 0 || outToken.balance == 0) ? (0,0) : ( _spotAmount(_tokens,inToken.balance, outToken.balance), _tokensToLiq( _tokens, _spotAmount(_tokens,inToken.balance, outToken.balance) ) ); return OrderDetails(secondAmount, liqAmount); } function getWithdrawDetails(uint128 _tokens) external override view returns (OrderDetails) { (uint128 amountX, uint128 amountY) = (detailsX_.balance == 0 || detailsY_.balance == 0) ? (0,0) : _liqToTokens(_tokens,total_supply_, detailsX_.balance, detailsY_.balance); return OrderDetails(amountX, amountY); } /* ---------------------------------------------------------------------------------- */ /* Pool Operations */ function swap(address _tokenAddress, uint256 _senderKey, address _senderOwner, uint128 _tokens, uint128 _minReturn) external override forCustomers { _expireTransactions(); uint256 owner = _processCustomer(_senderKey, _senderOwner); // sets owner from pubkey and address require(!_hasTransaction(owner), DEX.ERROR_ALREADY_IN_TRANSACTION); (Token inToken, Token outToken, bool xy) = _processToken(_tokenAddress); // does checks and fills variables with token details uint128 outAmount = _effectiveAmount(_tokens,inToken.balance, outToken.balance, fee_); require(outAmount >= _minReturn, DEX.ERROR_MIN_RETURN_NOT_ACHIEVED); require(outToken.balance >= MIN_TOKEN_AMOUNT + _minReturn, DEX.ERROR_NOT_ENOUGH_LIQUIDITY); address from = _expectedAddress(inToken.root, _senderKey, _senderOwner); Transaction tr = Transaction( now, _senderKey, _senderOwner, Operation.SWAP, xy, 0, _tokens, 0, 0, _minReturn ); transactions_.add(owner, tr); ITIP3WalletNotify(from).internalTransferFromNotify{value: CUSTOMER_FEE, bounce: true}(inToken.wallet, _tokens, address(this)); } function deposit(address _tokenAddress, uint256 _senderKey, address _senderOwner, uint128 _tokens, uint128 _maxSpend) external override forCustomers { _expireTransactions(); uint256 owner = _processCustomer(_senderKey, _senderOwner); // sets owner from pubkey and address require(!_hasTransaction(owner), DEX.ERROR_ALREADY_IN_TRANSACTION); (Token inToken, Token outToken, bool xy) = _processToken(_tokenAddress); // does checks and fills variables with token details // if it is first deposit, maxSpend is your desired amount of second token uint128 outAmount = (inToken.balance == 0 || outToken.balance == 0) ? _maxSpend : _spotAmount(_tokens,inToken.balance, outToken.balance); require(outAmount <= _maxSpend, DEX.ERROR_MAX_GRAB_NOT_ACHIEVED); require(outAmount >= MIN_TOKEN_AMOUNT && _tokens >= MIN_TOKEN_AMOUNT, DEX.ERROR_NOT_ENOUGH_LIQUIDITY); address fromIn = _expectedAddress(inToken.root, _senderKey, _senderOwner); Transaction tr = Transaction( now, _senderKey, _senderOwner, Operation.DEPOSIT, xy, 0, _tokens, outAmount, 0, _maxSpend ); transactions_.add(owner, tr); ITIP3WalletNotify(fromIn).internalTransferFromNotify{value: CUSTOMER_FEE, bounce: true}(inToken.wallet, _tokens, address(this)); } function withdraw(uint256 _senderKey, address _senderOwner, uint128 _tokens) external override forCustomers { _expireTransactions(); uint256 owner = _processCustomer(_senderKey, _senderOwner); // sets owner from pubkey and address require(!_hasTransaction(owner), DEX.ERROR_ALREADY_IN_TRANSACTION); require(detailsX_.balance > 0 && detailsY_.balance > 0, DEX.ERROR_NOT_ENOUGH_LIQUIDITY); require(_tokens >= _minWithdrawLiq(total_supply_, detailsX_.balance, detailsY_.balance), DEX.ERROR_NOT_ENOUGH_LIQUIDITY); // init transaction Transaction tr = Transaction( now, _senderKey, _senderOwner, Operation.WITHDRAW, true, 0, 0, 0, _tokens, 0 ); transactions_.add(owner, tr); address from = _expectedAddress(address(this), _senderKey, _senderOwner); ITIP3WalletRootBurnable(from).internalBurnFromRoot{value: CUSTOMER_FEE, bounce: true}(_tokens, address(this)); } /* ---------------------------------------------------------------------------------- */ /* Callbacks from TIP-3 */ function _deployWallets() internal view { ITIP3RootFungible(tokenX_).deployEmptyWallet{ callback: DEXPool.onWalletDeploy, value: DEPLOY_FEE + USAGE_FEE + MESSAGE_FEE }(0, 0, address(this), DEPLOY_FEE); ITIP3RootFungible(tokenY_).deployEmptyWallet{ callback: DEXPool.onWalletDeploy, value: DEPLOY_FEE + USAGE_FEE + MESSAGE_FEE }(0, 0, address(this), DEPLOY_FEE); } // callback from TIP-3 token root function onWalletDeploy(address walletAddress, TvmCell code) public forCallbacks { if ( msg.sender == tokenX_ && detailsX_.wallet == ZERO_ADDRESS) { detailsX_.wallet = walletAddress; //detailsX_.code = code; } else if (msg.sender == tokenY_ && detailsY_.wallet == ZERO_ADDRESS) { detailsY_.wallet = walletAddress; //detailsY_.code = code; } } ///@notice Callback from LiquidityWallet function onWalletBurn(address _tokenAddress, uint256 _senderKey, address _senderOwner, uint128 _tokens) public override forCallbacks { require(_tokenAddress == address(this),DEX.ERROR_UNKNOWN_TOKEN); address senderAddr = _expectedAddress(_tokenAddress, _senderKey, _senderOwner); require(msg.sender == senderAddr, DEX.ERROR_NOT_AUTHORIZED); uint256 owner = _processCustomer(_senderKey, _senderOwner); // sets owner from pubkey and address Transaction tr = _processTransaction(owner); if (tr.operation == Operation.WITHDRAW && tr.stage == 0) { if (tr.amountLiq == _tokens) { tr.amountIn = math.muldiv(_tokens, detailsX_.balance, total_supply_); tr.amountOut = _spotAmount(tr.amountIn, detailsX_.balance, detailsY_.balance); ITIP3WalletFungible(detailsX_.wallet).internalTransferFrom{value: USAGE_FEE, bounce: true}(senderAddr, tr.amountIn); ITIP3WalletFungible(detailsY_.wallet).internalTransferFrom{value: USAGE_FEE, bounce: true}(senderAddr, tr.amountOut); _savepoint(owner, tr); _commit(owner); // pre-last command of whole transaction } else { _rollback(owner); } } } ///@notice Callback from TIP-3 internalTransferNotify() function function onWalletReceive(address _tokenAddress, uint256 _receiverKey, address _receiverOwner, uint256 _senderKey, address _senderOwner, uint128 _tokens) public override forCallbacks { (Token inToken, Token outToken, bool xy) = _processToken(_tokenAddress); // does checks and fills variables with token details require(msg.sender == inToken.wallet, DEX.ERROR_NOT_AUTHORIZED); uint256 owner = _processCustomer(_senderKey, _senderOwner); // sets owner from pubkey and address Transaction tr = _processTransaction(owner); if (tr.operation == Operation.SWAP && tr.stage == 0 && tr.amountIn == _tokens) { tr.amountOut = _effectiveAmount(_tokens,inToken.balance, outToken.balance, fee_); if (tr.amountOut >= tr.limit) { address to = _expectedAddress(outToken.root, _senderKey, _senderOwner); _savepoint(owner, tr); _commit(owner); // finish transaction ITIP3WalletFungible(outToken.wallet).internalTransferFrom{value: TVM.FLAG_VALUE_ADD_INBOUND, bounce: true}(to, tr.amountOut); } else { _rollback(owner); } } else if (tr.operation == Operation.DEPOSIT && tr.stage == 0 &&tr.amountIn == _tokens) { tr.stage = 1; tr.amountOut = (inToken.balance == 0 || outToken.balance == 0) ? tr.limit : _spotAmount(_tokens, inToken.balance, outToken.balance); _savepoint(owner, tr); address fromOut = _expectedAddress(outToken.root, _senderKey, _senderOwner); ITIP3WalletNotify(fromOut).internalTransferFromNotify{flag: TVM.FLAG_VALUE_ADD_INBOUND, bounce: true}(outToken.wallet, tr.amountOut, address(this)); } else if (tr.operation == Operation.DEPOSIT && tr.stage == 1 &&tr.amountOut == _tokens) { address to = _expectedAddress(address(this), _senderKey, _senderOwner); _savepoint(owner, tr); _commit(owner); // finish transaction ITIP3WalletFungible(to).accept{flag: TVM.FLAG_VALUE_ADD_INBOUND, bounce: true}(_tokensToLiq(tr.amountIn,tr.amountOut)); } } /* ---------------------------------------------------------------------------------- */ /* Modifiers */ modifier forDEX() { require(msg.sender == dex_, DEX.ERROR_NOT_AUTHORIZED); _; // BODY msg.sender.transfer({ value: 0, flag: 64 }); } modifier forCallbacks() { require(msg.value >= CALLBACK_FEE, DEX.ERROR_NOT_ENOUGH_VALUE); //tvm.rawReserve(math.max(INITIAL_GAS, address(this).balance - msg.value), 2); _; // BODY //msg.sender.transfer({ value: 0, flag: TVM.FLAG_ALL_BALANCE }); } modifier forCustomers() { tvm.accept(); // for tests // later: msg.value() >= CUSTOMER_FEE require(_hasWallets(),DEX.ERROR_POOL_WALLETS_NOT_ADDED); _; // BODY // later: msg.sender.transfer({ value: 0, flag: TVM.FLAG_ALL_BALANCE }); } /* ---------------------------------------------------------------------------------- */ /* Private Part */ function _expireTransactions() private { optional(uint256, Transaction) minRecord = transactions_.min(); if (minRecord.hasValue()) { (uint256 minUser, Transaction minTrans) = minRecord.get(); if (now >= minTrans.created + 1 minutes) { _rollback(minUser); } while(true) { optional(uint256, Transaction) nextRecord = transactions_.next(minUser); if (nextRecord.hasValue()) { (uint256 nextUser, Transaction nextTrans) = nextRecord.get(); if (now >= nextTrans.created + 1 minutes) { _rollback(nextUser); } minUser = nextUser; } else { break; } } } } ///@notice Balance update at the end of transaction function _commit(uint256 user) private { Transaction tr = transactions_.fetch(user).get(); if (tr.operation == Operation.WITHDRAW) { total_supply_ = sub(total_supply_,tr.amountLiq); if (tr.xy) { detailsX_.balance = sub(detailsX_.balance,tr.amountIn); detailsY_.balance = sub(detailsY_.balance,tr.amountOut); } else { detailsY_.balance = sub(detailsY_.balance,tr.amountIn); detailsX_.balance = sub(detailsX_.balance,tr.amountOut); } } else if (tr.operation == Operation.DEPOSIT) { total_supply_ = add(total_supply_,tr.amountLiq); if (tr.xy) { detailsX_.balance = add(detailsX_.balance,tr.amountIn); detailsY_.balance = add(detailsY_.balance,tr.amountOut); } else { detailsY_.balance = add(detailsY_.balance,tr.amountIn); detailsX_.balance = add(detailsX_.balance,tr.amountOut); } } else if (tr.operation == Operation.SWAP) { if (tr.xy) { detailsX_.balance = add(detailsX_.balance,tr.amountIn); detailsY_.balance = sub(detailsY_.balance,tr.amountOut); } else { detailsY_.balance = add(detailsY_.balance,tr.amountIn); detailsX_.balance = sub(detailsX_.balance,tr.amountOut); } } delete transactions_[user]; } function _rollback(uint256 user) private { Transaction tr = transactions_.fetch(user).get(); if (tr.operation == Operation.DEPOSIT && tr.stage == 1) { (address from, address to) = (tr.xy) ? (detailsX_.wallet, _expectedAddress(detailsX_.root, tr.extOwner, tr.intOwner)) : (detailsY_.wallet, _expectedAddress(detailsY_.root, tr.extOwner, tr.intOwner)); ITIP3WalletFungible(from).internalTransferFrom{value: MESSAGE_FEE, bounce: true}(to, tr.amountIn); } delete transactions_[user]; } function _savepoint(uint256 user, Transaction tr) private inline { transactions_.getReplace(user, tr); } function _checkToken(address _token) private inline view returns(bool) { return tokenX_ == _token || tokenY_ == _token; } function _hasTransaction(uint256 owner) private inline view returns (bool) { return transactions_.exists(owner); } ///@notice Internal function for processing incoming counterparty information (its ) function _processCustomer(uint256 _senderKey, address _senderOwner) private pure returns (uint256) { uint256 owner; if (_senderKey != 0 && _senderOwner == ZERO_ADDRESS) { owner = _senderKey; } else if (_senderKey == 0 && _senderOwner != ZERO_ADDRESS) { owner = _senderOwner.value; } else { revert(DEX.ERROR_NOT_AUTHORIZED); } return owner; } function _processToken(address _tokenAddress) private view returns (Token inToken, Token outToken, bool xy) { if (_tokenAddress == tokenX_) { return (detailsX_, detailsY_, true); } else if (_tokenAddress == tokenY_) { return (detailsY_, detailsX_, false); } else { revert(DEX.ERROR_UNKNOWN_TOKEN); } } function _processTransaction(uint256 owner) private view returns (Transaction) { optional(Transaction) opt = transactions_.fetch(owner); if (opt.hasValue()) { return opt.get(); } else { revert(DEX.ERROR_UNKNOWN_TRANSACTION); } } function _hasWallets() private inline view returns (bool) { return detailsX_.wallet != ZERO_ADDRESS && detailsY_.wallet != ZERO_ADDRESS; } function _isContract() private inline pure returns (bool) { return msg.sender != ZERO_ADDRESS; } function _reserveGas() private inline returns (bool) { tvm.rawReserve(math.max(INITIAL_GAS, address(this).balance + DEX_VALUE_FEE - msg.value), 2); } function _expectedAddress(address _token, uint256 walletPubkey, address walletOwner) private view returns (address) { TvmCell stateInit; if (_token == address(this)) { stateInit = tvm.buildStateInit({ contr: TIP3LiquidityWallet, varInit: { root_address_: address(this), wallet_public_key_: walletPubkey, wallet_owner_address_: walletOwner, name_: name_, symbol_: symbol_, decimals_: decimals_, code_: code_ }, pubkey: walletPubkey, code: code_ }); return address.makeAddrStd(0, tvm.hash(stateInit)); } else if (_token == tokenX_ || _token == tokenY_ ) { Token tk = (_token == tokenX_) ? detailsX_ : detailsY_; stateInit = tvm.buildStateInit({ contr: TIP3FungibleWallet, varInit: { root_address_: tk.root, wallet_public_key_: walletPubkey, wallet_owner_address_: walletOwner, name_: tk.name, symbol_: tk.symbol, decimals_: tk.decimals, code_: tk.code }, pubkey: walletPubkey, code: tk.code }); return address.makeAddrStd(0, tvm.hash(stateInit)); } else { return ZERO_ADDRESS; } } function add(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x + y) >= x, 301, ERROR_ADDITION_OVERFLOW); z = x + y; } function sub(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x - y) <= x, 302, ERROR_SUBTRACTION_OVERFLOW); z = x - y; } function mul(uint128 x, uint128 y) internal pure returns (uint128 z) { require(y == 0 || (z = x * y) / y == x, 303, ERROR_MULTIPLY_OVERFLOW); z = x * y; } function _effectiveAmount(uint128 amountIn , uint128 balanceIn, uint128 balanceOut, uint128 fee) internal pure returns (uint128) { return sub(balanceOut, math.muldiv(balanceIn, balanceOut, sub( add(balanceIn,amountIn), math.muldiv(amountIn, fee, uint128(1_000_000)) ) ) ); } function _spotAmount(uint128 inAmount, uint128 inBalance, uint128 outBalance) internal inline pure returns (uint128) { return math.muldiv(outBalance, inAmount, inBalance); } function _tokensToLiq(uint128 inAmountX, uint128 inAmountY) internal inline pure returns (uint128) { return math.muldivc(inAmountX, inAmountY, MIN_TOKEN_AMOUNT * MIN_TOKEN_AMOUNT); } function _liqToTokens(uint128 amountIn, uint128 supplyIn, uint128 balanceX, uint128 balanceY) internal pure returns (uint128 outAmountX, uint128 outAmountY) { outAmountX = math.muldiv(amountIn, balanceX, supplyIn) * MIN_TOKEN_AMOUNT; outAmountY = _spotAmount(outAmountX, balanceX, balanceY) * MIN_TOKEN_AMOUNT; } function _minDeposit(uint128 balanceX, uint128 balanceY) internal pure returns (uint128 outAmountX, uint128 outAmountY) { (outAmountX, outAmountY) = (balanceX > balanceY) ? (math.muldivc(MIN_TOKEN_AMOUNT, balanceX, balanceY), MIN_TOKEN_AMOUNT) : (MIN_TOKEN_AMOUNT, math.muldivc(MIN_TOKEN_AMOUNT, balanceY, balanceX)); } function _minWithdrawLiq(uint128 supplyIn, uint128 balanceX, uint128 balanceY) internal pure returns (uint128) { return (balanceX > balanceY) ? math.muldivc(MIN_TOKEN_AMOUNT, supplyIn, balanceY) : math.muldivc(MIN_TOKEN_AMOUNT, supplyIn, balanceX); } }
Calculates wallet address with defined public key (responsible)
function callWalletAddress(int8 workchainId, uint256 walletPubkey, address walletOwner) override external responsible view returns (address) { }
12,809,336
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // OpenZeppelin Contracts v4.4.1 (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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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 v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } /* ___ ___ | \ / \ | |\ | | | | |/ | | | |___/ \__/ w a s t ___e d___ | \ / \ | |\ | | | | |/ | | | |___/ \__/ */ // "ipfs://Qmdh1bfqEWwiYH9ctBEZPwEWA6WETQByieGsgcYYXwKBQ1/" //Dodo Sol pragma solidity >=0.7.0 <0.9.0; contract Dodo is ERC721, ERC721Enumerable, Ownable { using Strings for uint256; using SafeMath for uint256; string public baseURI; string public baseExtension = ".json"; uint256 public cost = 0.1 ether; //base cost uint256 public whitelistCost = 0.03 ether; // whitelist cost uint256 public maxSupply = 0; // max DODO supply uint256 public maxDodoMint = 30; // max one time mint amount uint256 public whiteListLength = 0; // whitelist length (<= max whitelist sopt) uint256 public maxWhitelistSpots = 300; // max whitelist spot mapping(address => bool) public whitelisted; // the whitelist bool public salePaused = true; // state of the base sell bool public pauseWhitelistSale = true; // state of the whitelisting sale bool public pauseWhitelisting = true; // state of whitelisting process constructor( string memory _initBaseURI, uint256 _firstsupply ) ERC721("WastedDodo", "WD") { setBaseURI(_initBaseURI, _firstsupply); } // OwnerMint function OwnerMint(uint256 _mintAmount) public onlyOwner { uint256 supply = totalSupply(); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } // public // mint token: base function mint(address _to, uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!salePaused, "sale is paused"); require(_mintAmount > 0, "minimum 1 to mint"); require(_mintAmount <= maxDodoMint, "mint amount exceeds the max allowed amount"); require((cost.mul(_mintAmount)) <= msg.value, "ether value is invalid"); require(supply + _mintAmount <= maxSupply, "selected amount will exceed total token amount"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, supply + i); } } // mint token: whitelist function mintFromWhiteList(address _to, uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!pauseWhitelistSale, "whitelist sale is paused"); require(whitelisted[_to] != false, "user not enlisted for whitelist"); require(_mintAmount > 0, "minimum 1 to mint"); require(_mintAmount <= maxDodoMint, "mint amount exceeds the max allowed amount"); require((whitelistCost.mul(_mintAmount)) <= msg.value, "ether value is invalid"); require(supply + _mintAmount <= maxSupply, "selected amount will exceed total token amount"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, supply + i); } } // user token list function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } // set mint cost function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } // set whitemint cost function setWhitelistCost(uint256 _newCost) public onlyOwner { whitelistCost = _newCost; } // set max allowed mint amount function setmaxDodoMint(uint256 _newmaxDodoMint) public onlyOwner { maxDodoMint = _newmaxDodoMint; } // set max whitelist spot function setmaxWhitelistSpots(uint256 _newmaxWhitelistSpots) public onlyOwner { maxWhitelistSpots = _newmaxWhitelistSpots; } // set baseURI function setBaseURI(string memory _newBaseURI, uint256 _supply) public onlyOwner { baseURI = _newBaseURI; maxSupply = _supply; } // set the state of sale function pause(bool _state) public onlyOwner { salePaused = _state; } // set the state of WhitelistSale function setpauseWhitelistSale(bool _state) public onlyOwner { pauseWhitelistSale = _state; } // set the state of Whitelisting function setPauseWhitelisting(bool _state) public onlyOwner { pauseWhitelisting = _state; } // whitelist sender: public function whitelistUser(address _user) public payable { require(whiteListLength < maxWhitelistSpots, "whitelist is filled"); require(whitelisted[_user] != true, "user already whitelisted"); require(!pauseWhitelisting, "whitelisting is paused"); whitelisted[_user] = true; whiteListLength ++; } // remove user from whitelist function removeWhitelistUser(address _user) public onlyOwner { whitelisted[_user] = false; whiteListLength --; } // withdraw all function withdrawAll() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
set the state of WhitelistSale
function setpauseWhitelistSale(bool _state) public onlyOwner { pauseWhitelistSale = _state; }
11,908,281
pragma solidity >=0.5.16; // SPDX-License-Identifier: MIT import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol"; /************************************************** */ /* no1s1 App Smart Contract */ /************************************************** */ contract no1s1App { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract No1s1Data no1s1Data; // State variable referencing the data contract uint256 private constant MEDITATION_PRICE = 0.01 ether; // Price per minute meditation in no1s1 uint256 private constant ESCROW_AMOUNT = 0.5 ether; // Escrow amount to be paid to meditate uint256 private constant MAX_DURATION = 60; // Maximum allowed duration to meditate per user in minutes // Minimum values for battery state of charge uint256 private constant FULL_VALUE = 75; uint256 private constant GOOD_VALUE = 45; uint256 private constant LOW_VALUE = 25; // Minimum duration for given battery state of charge uint256 private constant FULL_DURATION = 60; uint256 private constant GOOD_DURATION = 30; uint256 private constant LOW_DURATION = 10; // Mappings (key value pairs) mapping(address => uint256) authorizedBackends; // Mapping to store authorized backends that can call into the app contract /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // Emitted when new backend is de-/authorized event AuthorizedBackend(address backendAddress); event DeAuthorizedBackend(address backendAddress); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ /** * @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 that the contract calling into the data contract is authorized */ modifier requireBackend() { require(authorizedBackends[msg.sender] == 1, "Backend is not authorized"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * tells the App contract where to find the data of the app contract (address) */ constructor(address dataContract) { contractOwner = msg.sender; no1s1Data = No1s1Data(dataContract); // register msg.sender as first backend authorizeBackend(msg.sender); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev authorize app contract to call into data contract * @return A bool that is the current authorization status */ function authorizeBackend(address backendAddress) public requireContractOwner returns(bool) { authorizedBackends[backendAddress] = 1; emit AuthorizedBackend(backendAddress); return true; } /** * @dev deauthorize app contract to call into data contract * @return A bool that is the current authorization status */ function deAuthorizeBackend(address backendAddress) public requireContractOwner returns(bool) { delete authorizedBackends[backendAddress]; emit DeAuthorizedBackend(backendAddress); return true; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev function for backend to trigger storing the current state of no1s1 (daily) * Pass address of function caller to data contract to enable role modifier */ function setAccessabilityStatus(bool mode) external requireContractOwner { no1s1Data.setAccessabilityStatus(mode); } /** * @dev function for backend to trigger storing the current state of no1s1 (daily) * Pass address of function caller to data contract to enable role modifier */ function setOccupationStatus(bool mode) external requireContractOwner { no1s1Data.setOccupationStatus(mode); } /** * @dev function to log data in smart contract when broadcasting from backend to frontend */ function broadcastData(uint256 _Bcurrent,uint256 _Bvoltage, uint256 _BSOC,uint256 _Pvoltage, uint256 _Senergy, uint256 _Time) external requireBackend { no1s1Data.broadcastData(_Bcurrent, _Bvoltage, _BSOC, _Pvoltage, _Senergy, _Time, FULL_VALUE, GOOD_VALUE, LOW_VALUE); } /** * @dev function for backend to trigger storing the current state of no1s1 (daily) * Pass address of function caller to data contract to enable role modifier */ function no1s1InfoLog(uint256 _Time) external requireBackend { no1s1Data.no1s1InfoLog(_Time); } /** * @dev buy function to access no1s1, only pass _selectedDuration and _username! */ function buy(uint256 _selectedDuration, string calldata _username) external payable { no1s1Data.buy{value: msg.value}(_selectedDuration, msg.sender, _username, ESCROW_AMOUNT, MAX_DURATION, GOOD_DURATION, LOW_DURATION); } /** * @dev function to check whether QR code is valid and authorizes to unlock door * Pass address of function caller to data contract to enable role modifier */ function checkAccess(bytes32 _key) external requireBackend { no1s1Data.checkAccess(_key, GOOD_DURATION, LOW_DURATION); } /** * @dev function triggered by back-end shortly after access() function with sensor feedback * Pass address of function caller to data contract to enable role modifier */ function checkActivity(bool _pressureDetected, bytes32 _key) external requireBackend { no1s1Data.checkActivity(_pressureDetected, _key); } /** * @dev function triggered by user after leaving no1s1. resets the occupancy state, pays back escrow, and sends out confirmation NFT */ function exit(bool _doorOpened, uint256 _actualDuration, bytes32 _key) external requireBackend { no1s1Data.exit(_doorOpened, _actualDuration, _key); } /** * @dev function triggered by user after leaving no1s1. resets the occupancy state, pays back escrow, and sends out confirmation NFT */ function refundEscrow(string calldata _username) external { no1s1Data.refundEscrow(msg.sender, _username, MEDITATION_PRICE); } // call from data contract function isDataContractOperational() external view returns(bool) { return no1s1Data.isOperational(); } /** * @dev Get operating status of no1s1 (main state variables) */ function howAmI() external view returns (bool accessability, bool occupation, uint256 batteryState, uint256 totalUsers, uint256 totalDuration, uint256 myBalance) { return no1s1Data.howAmI(); } /** * @dev Get address of no1s1 */ function whoAmI() external view returns(address no1s1Address) { return no1s1Data.whoAmI(); } /** * @dev Get balance of no1s1 */ function howRichAmI() external view returns(uint256 no1s1Balance) { return no1s1Data.howRichAmI(); } /** * @dev get latest entries of UsageLog (max 10) */ function getUsageLog() external view returns(uint256[] memory users, uint256[] memory balances, uint256[] memory durations) { return no1s1Data.getUsageLog(); } /** * @dev retrieve values needed to buy meditation time */ function checkBuyStatus() external view returns(uint256 batteryState, uint256 availableMinutes, uint256 costPerMinute , uint256 lastUpdate) { return no1s1Data.checkBuyStatus(MEDITATION_PRICE, FULL_DURATION, GOOD_DURATION, LOW_DURATION); } /** * @dev retrieve the latest technical logs */ function checkLastTechLogs() external view returns(uint256 pvVoltage, uint256 systemPower, uint256 batteryChargeState, uint256 batteryCurrency, uint256 batteryVoltage) { return no1s1Data.checkLastTechLogs(); } /** * @dev retrieve user information with key (QR code) */ function checkUserKey(bytes32 _key) external view returns(uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow) { return no1s1Data.checkUserKey(_key); } /** * @dev retrieve user information with username */ function checkUserName(string calldata _username) external view returns(bytes32 qrCode, uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow) { return no1s1Data.checkUserName(msg.sender, _username); } } /********************************************************************************************/ /* Interface to Data Contract */ /********************************************************************************************/ //visibility (also in data contract) must be `external` and signature of functions must match! interface No1s1Data { function setAccessabilityStatus(bool mode) external; function setOccupationStatus(bool mode) external; function broadcastData(uint256 _Bcurrent,uint256 _Bvoltage, uint256 _BSOC,uint256 _Pvoltage, uint256 _Senergy, uint256 _Time, uint256 FULL_VALUE, uint256 GOOD_VALUE, uint256 LOW_VALUE) external; function no1s1InfoLog(uint256 _Time) external; function buy(uint256 _selectedDuration, address txSender, string calldata _username, uint256 ESCROW_AMOUNT, uint256 MAX_DURATION, uint256 GOOD_DURATION, uint256 LOW_DURATION) external payable; function checkAccess(bytes32 _key, uint256 GOOD_DURATION, uint256 LOW_DURATION) external; function checkActivity(bool _pressureDetected, bytes32 _key) external; function exit(bool _doorOpened, uint256 _actualDuration, bytes32 _key) external; function refundEscrow(address _sender, string calldata _username, uint256 MEDITATION_PRICE) external; function isOperational() external view returns(bool); function howAmI() external view returns (bool accessability, bool occupation, uint256 batteryState, uint256 totalUsers, uint256 totalDuration, uint256 myBalance); function whoAmI() external view returns(address no1s1Address); function howRichAmI() external view returns(uint256 no1s1Balance); function getUsageLog() external view returns(uint256[] memory users, uint256[] memory balances, uint256[] memory durations); function checkBuyStatus(uint256 MEDITATION_PRICE, uint256 FULL_DURATION, uint256 GOOD_DURATION, uint256 LOW_DURATION) external view returns(uint256 batteryState, uint256 availableMinutes, uint256 costPerMinute , uint256 lastUpdate); function checkLastTechLogs() external view returns(uint256 pvVoltage, uint256 systemPower, uint256 batteryChargeState, uint256 batteryCurrency, uint256 batteryVoltage); function checkUserKey(bytes32 _key) external view returns(uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow); function checkUserName(address, string calldata _username) external view returns(bytes32 qrCode, uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow); }
function triggered by back-end shortly after access() function with sensor feedback Pass address of function caller to data contract to enable role modifier/
function checkActivity(bool _pressureDetected, bytes32 _key) external requireBackend { no1s1Data.checkActivity(_pressureDetected, _key); }
12,788,234
./partial_match/1/0x27865916b3E6208b54EB7B3C481b3157e0Ac1B0E/sources/Pile.sol
drip updates the chi of the rate category by compounding the interest and updates the total debt
function drip(uint rate) public { if (now >= rates[rate].lastUpdated) { (uint chi, uint deltaInterest) = compounding(rates[rate].chi, rates[rate].ratePerSecond, rates[rate].lastUpdated, rates[rate].pie); rates[rate].chi = chi; rates[rate].lastUpdated = uint48(now); total = safeAdd(total, deltaInterest); } }
4,433,273
// SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <=0.7.0; contract Ballot { //Information about a voter struct Voter { uint weight; //weight is amount of vote the voter can have bool voted; //true implies voter already voted } //Candidate type for a single candidate struct Candidate { bytes32 name; // name up to 32 bytes uint voteCount; // total number of votes bytes32 partyName; string partySymbol; } bytes32 electionName; bytes32 electionDesc; address public admin; uint votingdeadline; constructor() { admin = msg.sender; } /* *This is a special type of func called modifier which is used to restrict the execution of certain transaction, where the admin only have the rights to do so * */ modifier onlyAdmin() { require(msg.sender == admin); _; } //Mapping is used to store the voters detail on the basis of their address mapping(address => Voter) public voters; address[] voterIndex; //Dynamnically-sized array of 'Candidate' structs Candidate[] public candidates; /* *This function creates a new election which requires two arguements electionname and voting duration * @param {bytes32} election * name of the election *@param {uint} duration * */ function createElection(bytes32 election, bytes32 desc, uint duration) public { delete candidates; deleteAllVoters(); delete voterIndex; electionName = election; votingdeadline = block.timestamp + (duration * 1 minutes); electionDesc = desc; } /* *This function is used to retrieve the election from the blockchain which returs a string . a helper func called bytes32ToString is used here to convert bytes32 to string *@return {string} elecName * name of an election */ function getElectionName() public view returns(string memory elecName) { elecName = bytes32ToString(electionName); } function getElectionDesc() public view returns(string memory elecDesc) { elecDesc = bytes32ToString(electionDesc); } /* *This getter function is used to get the voting deadline, * */ function getVotingDeadline() public view returns(uint) { return votingdeadline; } /* *This is a helper function which is used to convert the given bytes32 to string which is later required when we want to retrieve the output as a string *@param {bytes32} x * any bytes32 character *@return {string} */ function bytes32ToString(bytes32 x) public pure returns(string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } /* *This is a helper function which converts string to bytes32 *@param {string memory} source *string data type *@return {bytes32} result *result in bytes32 */ function stringToBytes32(string memory source) public pure returns(bytes32 result) { assembly { result := mload(add(source, 32)) } } /* *This function is used to add candidates to the blockchin, which requires three arguements such as candidatename, partyname and party symbol image *@param {bytes32} candid *name of the candidate *@param {bytes32} symbol *symbol of an image *@param {bytes32} party *party name *@return {bytes32} c *a new Candidate object */ function addCandidate(bytes32 candidateName, bytes32 partyName, string memory symbol) public { candidates.push(Candidate({ name: candidateName, partyName: partyName, partySymbol: symbol, voteCount: 0 })); } /* *This function returns a number of candidates added to the blockchain *@return {uint256} length *the number of candidates added to the blockchain */ function getCandidateLength() public view returns(uint256 length) { length = candidates.length; } /* *This function retrieves the name of the candidate , provided the index of a candidate and is converted to string *@param {uint} index *index of the candidate *@return {string} candid * name of the candidate */ function getCandidate(uint index) public view returns(string memory candid) { candid = bytes32ToString(candidates[index].name); } /* *This function is retrieves the candidate party name from the blockchain and is converted to string *@param {uint} index *index of the candidate *@return {string} party *party name */ function getCandidatePartyName(uint index) public view returns(string memory party) { party = bytes32ToString(candidates[index].partyName); } /* *This function is retrieves the candidate party symbol from the blockchain and is converted to string *@param {uint} index *index of the candidate *@return {string} symb *party symbol image */ function getCandidatePartySymbol(uint index) public view returns(string memory symb) { symb = candidates[index].partySymbol; } /* *This function is used to retrieve the candidate details *@param {uint} index *index of the candidate *@return {string} candid *candidate name *@return {string} symb *symbol image */ function getCandidateDetails(uint index) public view returns(string memory candidate, string memory partyName, string memory symb) { candidate = bytes32ToString(candidates[index].name); partyName = bytes32ToString(candidates[index].partyName); symb = candidates[index].partySymbol; } /* *Admin only gives 'voter' right to vote on the ballot *@param {address} voter *address of the voter * */ function giveRightToVote(address voter) public onlyAdmin { require(msg.sender == admin); require(!voters[voter].voted); voters[voter].weight = 1; } /* *his function adds voters to the blockchain and Admin only have the rights to add the voters * @param {address} voter * address of the voter * */ function addVoter(address voter) public { bool exist = voterExist(voter); if(!exist) { voterIndex.push(voter); } } function voterExist(address voter) public view returns(bool) { for(uint i=0; i< voterIndex.length; i++) { if(voterIndex[i] == voter){ return true; } } return false; } function deleteAllVoters() public { for(uint i=0; i<voterIndex.length; i++) { if(voterExist(voterIndex[i])) { delete voters[voterIndex[i]]; } } } function getVoter(uint index) public view returns (address) { return voterIndex[index]; } function getVotersLength() public view returns(uint votersLength) { votersLength = voterIndex.length; } /* *This function checks if candidate already exist * @param {bytes32} candidate * candidate name in bytes32 *@return {bool} *a boolean value */ function validCandidate(bytes32 candidate) public view returns(bool) { for (uint i = 0; i < candidates.length; i++) { if (candidates[i].name == candidate) { return true; } } return false; } /* *This function is used to commit vote to their preferred candidate * @param {bytes32} candidateName * candidate name *@return {bool} check *boolean value */ function vote(bytes32 candidateName) public { Voter storage sender = voters[msg.sender]; require(block.timestamp < votingdeadline, 'voting period ended already'); require(!sender.voted); sender.voted = true; sender.weight = 1; for (uint i = 0; i < candidates.length; i++) { if (candidates[i].name == candidateName) { candidates[i].voteCount += sender.weight; } } addVoter(msg.sender); } /* *This function gets the number of vote count of each candidate on the basis of their index *@param {uint} index *index of the candidate *@return {uint} voteCount *the number of commited vote of each candidate */ function getCandidateVoteCount(uint index) public view returns(uint voteCount) { return candidates[index].voteCount; } /* /*This function retrieves the total numbers of committed votes to all the candidates *@return {uint} count *toal number of accumulated votes of all the candidates */ function getTotalVotes() public view returns(uint count) { count = 0; for (uint i = 0; i < candidates.length; i++) { count += candidates[i].voteCount; } } /* *This function returns true if voters has already voted to make sure that the voters are not allowed to vote twice *@param {address} voter *address of the voter *@return {bool} voted *boolean value */ function getVoted(address voter) public view returns(bool voted) { if (voters[voter].voted == true) { return true; } return false; } /* *Automatic calculation of winning candidate with all votes of the voters * @return {uint} winningCandidate * the highest number of votes * */ function winningCandidate() public view returns(uint winner) { uint winningVoteCount = 0; for (uint i = 0; i < candidates.length; i++) { if (candidates[i].voteCount > winningVoteCount) { winningVoteCount = candidates[i].voteCount; winner = i; } } } /* *This is a readonly function which returns the name of the winnner candidate *@return {string} winnerName *winner name */ function winnerName() public view returns(string memory winner) { winner = bytes32ToString(candidates[winningCandidate()].name); } function sendEther(address payable recipient) external { recipient.transfer(0.1 ether); } function balanceOf() external view returns(uint) { return address(this).balance; } receive() external payable { if(msg.value < 1000) { revert(); } } }
This is a helper function which converts string to bytes32 {string memory} sourcestring data typereturn {bytes32} resultresult in bytes32/
function stringToBytes32(string memory source) public pure returns(bytes32 result) { assembly { result := mload(add(source, 32)) } }
6,377,367
./full_match/42/0xb397fc77aC18DDD3Ead391a3Ca64892817De881C/sources/browser/flatten.sol
Increase rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove by dividing it by cumulativeFeeMutliplier. 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 removed and rawCollateral credited. : 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 `totalPositionCollateral`.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getCollateral(rawCollateral).sub(initialBalance); }
16,255,885
./partial_match/1/0x000000000000f968845afB0B8Cf134Ec196D38D4/sources/contracts/controller/ArrngController.sol
setOracleAddress: set a new oracle address oracle_: the new oracle address/
function setOracleAddress(address payable oracle_) external onlyOwner { require(oracle_ != address(0), "Oracle address cannot be address(0)"); oracleAddress = oracle_; emit OracleAddressSet(oracle_); }
15,927,252
./full_match/40/0x110dE362cc436D7f54210f96b8C7652C2617887D/sources/contracts/LiquidityManager.sol
Get or create a pool for (tokenX/tokenY/fee) if not exists. tokenX tokenX of swap pool tokenY tokenY of swap pool fee fee amount of swap pool initialPoint initial point if need to create a new pool return corresponding pool address
function createPool(address tokenX, address tokenY, uint24 fee, int24 initialPoint) external returns (address) { require(tokenX < tokenY, "x<y"); address pool = IiZiSwapFactory(factory).pool(tokenX, tokenY, fee); if (pool == address(0)) { pool = IiZiSwapFactory(factory).newPool(tokenX, tokenY, fee, initialPoint); return pool; } return pool; }
9,551,876
./partial_match/1/0xEC233143B85892dd6A6E2dc48D7F73aF728d7164/sources/alch.sol
See {IERC20-balanceOf}./
function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; }
2,622,269
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function totalSupply()public view returns (uint total_Supply); function balanceOf(address who)public view returns (uint256); function allowance(address owner, address spender)public view returns (uint); function transferFrom(address from, address to, uint value)public returns (bool ok); function approve(address spender, uint value)public returns (bool ok); function transfer(address to, uint value)public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract FlexionCoin is ERC20 { using SafeMath for uint256; string public constant name = "FLEXION"; // Name of the token string public constant symbol = "FXN"; // Symbol of token uint8 public constant decimals = 18; uint public _totalsupply = 360000000 * 10 ** 18; // 360 million total supply // muliplies dues to decimal precision address public owner; // Owner of this contract uint256 public _price_token_PRE = 16000; // 1 Ether = 16000 tokens in Pre-ICO uint256 public _price_token_ICO1 = 8000; // 1 Ether = 8000 tokens in ICO Phase 1 uint256 public _price_token_ICO2 = 4000; // 1 Ether = 4000 tokens in ICO Phase 2 uint256 public _price_token_ICO3 = 2666; // 1 Ether = 2666 tokens in ICO Phase 3 uint256 public _price_token_ICO4 = 2000; // 1 Ether = 2000 tokens in ICO Phase 4 uint256 no_of_tokens; uint256 bonus_token; uint256 total_token; bool stopped = false; uint256 public pre_startdate; uint256 public ico1_startdate; uint256 ico_first; uint256 ico_second; uint256 ico_third; uint256 ico_fourth; uint256 pre_enddate; uint256 public eth_received; // Total ether received in the contract uint256 maxCap_public = 240000000 * 10 ** 18; // 240 million in Public Sale mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; enum Stages { NOTSTARTED, PREICO, ICO, PAUSED, ENDED } Stages public stage; modifier atStage(Stages _stage) { if (stage != _stage) // Contract not in expected state revert(); _; } modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } function FlexionCoin() public { owner = msg.sender; balances[owner] = 120000000 * 10 ** 18; // 100 million to owner & 20 million to referral bonus stage = Stages.NOTSTARTED; Transfer(0, owner, balances[owner]); } function () public payable { require(stage != Stages.ENDED); require(!stopped && msg.sender != owner); if( stage == Stages.PREICO && now <= pre_enddate ) { require (eth_received <= 1500 ether); // Hardcap eth_received = (eth_received).add(msg.value); no_of_tokens = ((msg.value).mul(_price_token_PRE)); require (no_of_tokens >= (500 * 10 ** 18)); // 500 min purchase bonus_token = ((no_of_tokens).mul(50)).div(100); // 50% bonus in Pre-ICO total_token = no_of_tokens + bonus_token; transferTokens(msg.sender,total_token); } else if (stage == Stages.ICO && now <= ico_fourth ) { if( now < ico_first ) { no_of_tokens = (msg.value).mul(_price_token_ICO1); require (no_of_tokens >= (100 * 10 ** 18)); // 100 min purchase bonus_token = ((no_of_tokens).mul(40)).div(100); // 40% bonus in ICO Phase 1 total_token = no_of_tokens + bonus_token; transferTokens(msg.sender,total_token); } else if( now >= ico_first && now < ico_second ) { no_of_tokens = (msg.value).mul(_price_token_ICO2); require (no_of_tokens >= (100 * 10 ** 18)); // 100 min purchase bonus_token = ((no_of_tokens).mul(30)).div(100); // 30% bonus in ICO Phase 2 total_token = no_of_tokens + bonus_token; transferTokens(msg.sender,total_token); } else if( now >= ico_second && now < ico_third ) { no_of_tokens = (msg.value).mul(_price_token_ICO3); require (no_of_tokens >= (100 * 10 ** 18)); // 100 min purchase bonus_token = ((no_of_tokens).mul(20)).div(100); // 20% bonus in ICO Phase 3 total_token = no_of_tokens + bonus_token; transferTokens(msg.sender,total_token); } else if( now >= ico_third && now < ico_fourth ) { no_of_tokens = (msg.value).mul(_price_token_ICO4); require (no_of_tokens >= (100 * 10 ** 18)); // 100 min purchase bonus_token = ((no_of_tokens).mul(10)).div(100); // 10% bonus in ICO Phase 4 total_token = no_of_tokens + bonus_token; transferTokens(msg.sender,total_token); } } else { revert(); } } function start_PREICO() public onlyOwner atStage(Stages.NOTSTARTED) { stage = Stages.PREICO; stopped = false; balances[address(this)] = maxCap_public; pre_startdate = now; pre_enddate = now + 30 days; // 30 days PREICO Transfer(0, address(this), balances[address(this)]); } function start_ICO() public onlyOwner atStage(Stages.PREICO) { require(now > pre_enddate); stage = Stages.ICO; stopped = false; ico1_startdate = now; ico_first = now + 15 days; ico_second = ico_first + 15 days; ico_third = ico_second + 15 days; ico_fourth = ico_third + 15 days; Transfer(0, address(this), balances[address(this)]); } // called by the owner, pause ICO function PauseICO() external onlyOwner { stopped = true; } // called by the owner, resumes ICO function ResumeICO() external onlyOwner { stopped = false; } function end_ICO() external onlyOwner atStage(Stages.ICO) { require(now > ico_fourth); stage = Stages.ENDED; _totalsupply = (_totalsupply).sub(balances[address(this)]); balances[address(this)] = 0; Transfer(address(this), 0 , balances[address(this)]); } // what is the total supply of the ech tokens function totalSupply() public view returns (uint256 total_Supply) { total_Supply = _totalsupply; } // What is the balance of a particular account? function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) public returns (bool success) { require( _to != 0x0); require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount >= 0); balances[_from] = (balances[_from]).sub(_amount); allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(_from, _to, _amount); return true; } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public returns (bool success) { require( _spender != 0x0); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { require( _owner != 0x0 && _spender !=0x0); return allowed[_owner][_spender]; } // Transfer the balance from owner&#39;s account to another account function transfer(address _to, uint256 _amount) public returns (bool success) { require( _to != 0x0); require(balances[msg.sender] >= _amount && _amount >= 0); balances[msg.sender] = (balances[msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(msg.sender, _to, _amount); return true; } // Transfer the balance from owner&#39;s account to another account function transferTokens(address _to, uint256 _amount) private returns (bool success) { require( _to != 0x0); require(balances[address(this)] >= _amount && _amount > 0); balances[address(this)] = (balances[address(this)]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(address(this), _to, _amount); return true; } function drain() external onlyOwner { owner.transfer(this.balance); } }
Transfer the balance from owner&39;s account to another account
function transfer(address _to, uint256 _amount) public returns (bool success) { require( _to != 0x0); require(balances[msg.sender] >= _amount && _amount >= 0); balances[msg.sender] = (balances[msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); Transfer(msg.sender, _to, _amount); return true; }
7,903,221
/** *Submitted for verification at Etherscan.io on 2021-07-19 */ // SPDX-License-Identifier: GPL-3.0 // 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: @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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol 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 SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/vaults/yearnv2/v032/BaseStrategy.sol pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; struct StrategyParams { uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); function vaultAdapter() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function apiVersion() external pure returns (string memory); function keeper() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } /** * @title Yearn Base Strategy * @author yearn.finance (original) & gro protocol (modified) * @notice Modified version of Base Strategy v.0.3.2 */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.2"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyOwner() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public view virtual returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external { require(msg.sender == vault.vaultAdapter(), 'harvest: Call from vaultAdapter'); uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition( totalAssets > debtOutstanding ? totalAssets : debtOutstanding ); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyOwner { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } abstract contract BaseStrategyInitializable is BaseStrategy { event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) {} function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function clone(address _vault) external returns (address) { return this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper); emit Cloned(newStrategy); } } // File: contracts/vaults/yearnv2/v032/strategies/GenericLevComp.sol /** *Submitted for verification at Etherscan.io on 2021-07-01 */ pragma solidity 0.6.12; // Part: Account library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } // Part: Actions library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } // Part: ICallee /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } // Part: ISoloMargin interface ISoloMargin { struct OperatorArg { address operator1; bool trusted; } function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } // Part: IUni interface IUni{ function getAmountsOut( uint256 amountIn, address[] calldata path ) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Part: InterestRateModel interface InterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256, uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/Math /** * @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); } } // Part: Types library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } // Part: CTokenI interface CTokenI { /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function accrualBlockNumber() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } // Part: DydxFlashloanBase contract DydxFlashloanBase { using SafeMath for uint256; function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0}), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } // Part: CErc20I interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenI cTokenCollateral ) external returns (uint256); function underlying() external view returns (address); } // Part: ComptrollerI interface ComptrollerI { function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); /*** Comp claims ****/ function claimComp(address holder) external; function claimComp(address holder, CTokenI[] memory cTokens) external; function markets(address ctoken) external view returns ( bool, uint256, bool ); function compSpeeds(address ctoken) external view returns (uint256); } // File: Strategy.sol /******************** * * A lender optimisation strategy for any erc20 asset * https://github.com/Grandthrax/yearnV2-generic-lender-strat * v0.2.2 * ********************* */ /// @notice Fork of Yearns Leveraged comp farming strategy /// @author yearn.finance contract GenericLevComp is BaseStrategy, DydxFlashloanBase, ICallee { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan); //Flash Loan Providers address private constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; // Comptroller address for compound.finance ComptrollerI public constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //Only three tokens we use address public constant comp = address(0xc00e94Cb662C3520282E6f5717214004A7f26888); CErc20I public cToken; //address public constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //Operating variables uint256 public collateralTarget = 0.73 ether; // 73% uint256 public blocksToLiquidationDangerZone = 46500; // 7 days = 60*60*24*7/13 uint256 public minWant = 0; //Only lend if we have enough want to be worth it. Can be set to non-zero uint256 public minCompToSell = 0.1 ether; //used both as the threshold to sell but also as a trigger for harvest //To deactivate flash loan provider if needed bool public DyDxActive = true; bool public forceMigrate = false; uint256 public dyDxMarketId; constructor(address _vault, address _cToken) public BaseStrategy(_vault) { cToken = CErc20I(address(_cToken)); //pre-set approvals IERC20(comp).safeApprove(uniswapRouter, uint256(-1)); want.safeApprove(address(cToken), uint256(-1)); want.safeApprove(SOLO, uint256(-1)); // You can set these parameters on deployment to whatever you want maxReportDelay = 86400; // once per 24 hours profitFactor = 100; // multiple before triggering harvest _setMarketIdFromTokenAddress(); } function name() external override view returns (string memory){ return "StrategyGenericLevCompFarm"; } /* * Control Functions */ function setDyDx(bool _dydx) external management { DyDxActive = _dydx; } function setForceMigrate(bool _force) external onlyOwner { forceMigrate = _force; } function setMinCompToSell(uint256 _minCompToSell) external management { minCompToSell = _minCompToSell; } function setMinWant(uint256 _minWant) external management { minWant = _minWant; } function updateMarketId() external management { _setMarketIdFromTokenAddress(); } function setCollateralTarget(uint256 _collateralTarget) external management { (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); require(collateralFactorMantissa > _collateralTarget, "!dangerous collateral"); collateralTarget = _collateralTarget; } /* * Base External Facing Functions */ /* * An accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of want tokens. */ function estimatedTotalAssets() public override view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 _claimableComp = predictCompAccrued(); uint256 currentComp = IERC20(comp).balanceOf(address(this)); // Use touch price. it doesnt matter if we are wrong as this is not used for decision making uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp)); uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist return want.balanceOf(address(this)).add(deposits).add(conservativeWant).sub(borrows); } //predicts our profit at next report function expectedReturn() public view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets - debt; } } /* * Provide a signal to the keeper that `tend()` should be called. * (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * tendTrigger should be called with same gasCost as harvestTrigger */ function tendTrigger(uint256 gasCost) public override view returns (bool) { if (harvestTrigger(gasCost)) { //harvest takes priority return false; } if (getblocksUntilLiquidation() <= blocksToLiquidationDangerZone) { return true; } } /* * Provide a signal to the keeper that `harvest()` should be called. * gasCost is expected_gas_use * gas_price * (keepers are always reimbursed by yEarn) * * NOTE: this call and `tendTrigger` should never return `true` at the same time. */ function harvestTrigger(uint256 gasCost) public override view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if strategy is not activated if (params.activation == 0) return false; uint256 wantGasCost = priceCheck(weth, address(want), gasCost); uint256 compGasCost = priceCheck(weth, comp, gasCost); // after enough comp has accrued we want the bot to run uint256 _claimableComp = predictCompAccrued(); if (_claimableComp > minCompToSell) { // check value of COMP in wei if ( _claimableComp.add(IERC20(comp).balanceOf(address(this))) > compGasCost.mul(profitFactor)) { return true; } } // Should trigger if hadn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; //check if vault wants lots of money back // dont return dust uint256 outstanding = vault.debtOutstanding(); if (outstanding > profitFactor.mul(wantGasCost)) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! uint256 credit = vault.creditAvailable().add(profit); return (profitFactor.mul(wantGasCost) < credit); } //WARNING. manipulatable and simple routing. Only use for safe functions function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) { if (_amount == 0) { return 0; } address[] memory path; if(start == weth){ path = new address[](2); path[0] = weth; path[1] = end; }else{ path = new address[](3); path[0] = start; path[1] = weth; path[2] = end; } uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } /***************** * Public non-base function ******************/ //Calculate how many blocks until we are in liquidation based on current interest rates //WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look //equation. Compound doesn't include compounding for most blocks //((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate)); function getblocksUntilLiquidation() public view returns (uint256) { (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 borrrowRate = cToken.borrowRatePerBlock(); uint256 supplyRate = cToken.supplyRatePerBlock(); uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18); uint256 collateralisedDeposit = collateralisedDeposit1; uint256 denom1 = borrows.mul(borrrowRate); uint256 denom2 = collateralisedDeposit.mul(supplyRate); if (denom2 >= denom1) { return uint256(-1); } else { uint256 numer = collateralisedDeposit.sub(borrows); uint256 denom = denom1 - denom2; //minus 1 for this block return numer.mul(1e18).div(denom); } } // This function makes a prediction on how much comp is accrued // It is not 100% accurate as it uses current balances in Compound to predict into the past function predictCompAccrued() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } //comp speed is amount to borrow or deposit (so half the total distribution for want) uint256 distributionPerBlock = compound.compSpeeds(address(cToken)); uint256 totalBorrow = cToken.totalBorrows(); //total supply needs to be echanged to underlying using exchange rate uint256 totalSupplyCtoken = cToken.totalSupply(); uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18); uint256 blockShareSupply = 0; if(totalSupply > 0){ blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply); } uint256 blockShareBorrow = 0; if(totalBorrow > 0){ blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow); } //how much we expect to earn per block uint256 blockShare = blockShareSupply.add(blockShareBorrow); //last time we ran harvest uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block return blocksSinceLast.mul(blockShare); } //Returns the current position //WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between //cToken is very active so not normally an issue. function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) { (, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = cToken.getAccountSnapshot(address(this)); borrows = borrowBalance; deposits = ctokenBalance.mul(exchangeRate).div(1e18); } //statechanging version function getLivePosition() public returns (uint256 deposits, uint256 borrows) { deposits = cToken.balanceOfUnderlying(address(this)); //we can use non state changing now because we updated state with balanceOfUnderlying call borrows = cToken.borrowBalanceStored(address(this)); } //Same warning as above function netBalanceLent() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); return deposits.sub(borrows); } /*********** * internal core logic *********** */ /* * A core method. * Called at beggining of harvest before providing report to owner * 1 - claim accrued comp * 2 - if enough to be worth it we sell * 3 - because we lose money on our loans we need to offset profit from comp. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity. also reduces bytesize if (cToken.balanceOf(address(this)) == 0) { uint256 wantBalance = want.balanceOf(address(this)); //no position to harvest //but we may have some debt to return //it is too expensive to free more debt in this method so we do it in adjust position _debtPayment = Math.min(wantBalance, _debtOutstanding); return (_profit, _loss, _debtPayment); } (uint256 deposits, uint256 borrows) = getLivePosition(); //claim comp accrued _claimComp(); //sell comp _disposeOfComp(); uint256 wantBalance = want.balanceOf(address(this)); uint256 investedBalance = deposits.sub(borrows); uint256 balance = investedBalance.add(wantBalance); uint256 debt = vault.strategies(address(this)).totalDebt; //Balance - Total Debt is profit if (balance > debt) { _profit = balance - debt; if (wantBalance < _profit) { //all reserve is profit _profit = wantBalance; } else if (wantBalance > _profit.add(_debtOutstanding)){ _debtPayment = _debtOutstanding; }else{ _debtPayment = wantBalance - _profit; } } else { //we will lose money until we claim comp then we will make money //this has an unintended side effect of slowly lowering our total debt allowed _loss = debt - balance; _debtPayment = Math.min(wantBalance, _debtOutstanding); } } /* * Second core function. Happens after report call. * * Similar to deposit function from V1 strategy */ function adjustPosition(uint256 _debtOutstanding) internal override { //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } //we are spending all our cash unless we have debt outstanding uint256 _wantBal = want.balanceOf(address(this)); if(_wantBal < _debtOutstanding){ //this is graceful withdrawal. dont use backup //we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals if(cToken.balanceOf(address(this)) > 1){ _withdrawSome(_debtOutstanding - _wantBal); } return; } (uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true); //if we are below minimun want change it is not worth doing //need to be careful in case this pushes to liquidation if (position > minWant) { //if dydx is not active we just try our best with basic leverage if (!DyDxActive) { uint i = 0; while(position > 0){ position = position.sub(_noFlashLoan(position, deficit)); if(i >= 6){ break; } i++; } } else { //if there is huge position to improve we want to do normal leverage. it is quicker if (position > want.balanceOf(SOLO)) { position = position.sub(_noFlashLoan(position, deficit)); } //flash loan to position if(position > minWant){ doDyDxFlashLoan(deficit, position); } } } } /************* * Very important function * Input: amount we want to withdraw and whether we are happy to pay extra for Aave. * cannot be more than we have * Returns amount we were able to withdraw. notall if user has some balance left * * Deleverage position -> redeem our cTokens ******************** */ function _withdrawSome(uint256 _amount) internal returns (bool notAll) { (uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false); //If there is no deficit we dont need to adjust position //if the position change is tiny do nothing if (deficit && position > minWant) { //we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans if (DyDxActive) { position = position.sub(doDyDxFlashLoan(deficit, position)); } uint8 i = 0; //position will equal 0 unless we haven't been able to deleverage enough with flash loan //if we are not in deficit we dont need to do flash loan while (position > minWant.add(100)) { position = position.sub(_noFlashLoan(position, true)); i++; //A limit set so we don't run out of gas if (i >= 5) { notAll = true; break; } } } //now withdraw //if we want too much we just take max //This part makes sure our withdrawal does not force us into liquidation (uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition(); uint256 tempColla = collateralTarget; uint256 reservedAmount = 0; if(tempColla == 0){ tempColla = 1e15; // 0.001 * 1e18. lower we have issues } reservedAmount = borrowBalance.mul(1e18).div(tempColla); if(depositBalance >= reservedAmount){ uint256 redeemable = depositBalance.sub(reservedAmount); if (redeemable < _amount) { cToken.redeemUnderlying(redeemable); } else { cToken.redeemUnderlying(_amount); } } if(collateralTarget == 0 && want.balanceOf(address(this)) > borrowBalance){ cToken.repayBorrow(borrowBalance); } //let's sell some comp if we have more than needed //flash loan would have sent us comp if we had some accrued so we don't need to call claim comp _disposeOfComp(); } /*********** * This is the main logic for calculating how to change our lends and borrows * Input: balance. The net amount we are going to deposit/withdraw. * Input: dep. Is it a deposit or withdrawal * Output: position. The amount we want to change our current borrow position. * Output: deficit. True if we are reducing position size * * For instance deficit =false, position 100 means increase borrowed balance by 100 ****** */ function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) { //we want to use statechanging for safety (uint256 deposits, uint256 borrows) = getLivePosition(); //When we unwind we end up with the difference between borrow and supply uint256 unwoundDeposit = deposits.sub(borrows); //we want to see how close to collateral target we are. //So we take our unwound deposits and add or remove the balance we are are adding/removing. //This gives us our desired future undwoundDeposit (desired supply) uint256 desiredSupply = 0; if (dep) { desiredSupply = unwoundDeposit.add(balance); } else { if(balance > unwoundDeposit) balance = unwoundDeposit; desiredSupply = unwoundDeposit.sub(balance); } //(ds *c)/(1-c) uint256 num = desiredSupply.mul(collateralTarget); uint256 den = uint256(1e18).sub(collateralTarget); uint256 desiredBorrow = num.div(den); if (desiredBorrow > 1e5) { //stop us going right up to the wire desiredBorrow = desiredBorrow - 1e5; } //now we see if we want to add or remove balance // if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position if (desiredBorrow < borrows) { deficit = true; position = borrows - desiredBorrow; //safemath check done in if statement } else { //otherwise we want to increase position deficit = false; position = desiredBorrow - borrows; } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); uint256 assets = netBalanceLent().add(_balance); uint256 debtOutstanding = vault.debtOutstanding(); if(debtOutstanding > assets){ _loss = debtOutstanding - assets; } if (assets < _amountNeeded) { //if we cant afford to withdraw we take all we can //withdraw all we can (uint256 deposits, uint256 borrows) = getLivePosition(); //1 token causes rounding error with withdrawUnderlying if(cToken.balanceOf(address(this)) > 1){ _withdrawSome(deposits.sub(borrows)); } _amountFreed = Math.min(_amountNeeded, want.balanceOf(address(this))); } else { if (_balance < _amountNeeded) { _withdrawSome(_amountNeeded.sub(_balance)); //overflow error if we return more than asked for _amountFreed = Math.min(_amountNeeded, want.balanceOf(address(this))); }else{ _amountFreed = _amountNeeded; } } } function _claimComp() internal { CTokenI[] memory tokens = new CTokenI[](1); tokens[0] = cToken; compound.claimComp(address(this), tokens); } //sell comp function function _disposeOfComp() internal { uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > minCompToSell) { address[] memory path = new address[](3); path[0] = comp; path[1] = weth; path[2] = address(want); IUni(uniswapRouter).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now); } } //lets leave //if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered function prepareMigration(address _newStrategy) internal override { if(!forceMigrate){ (uint256 deposits, uint256 borrows) = getLivePosition(); _withdrawSome(deposits.sub(borrows)); (, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this)); require(borrowBalance < 10_000, "DELEVERAGE_FIRST"); IERC20 _comp = IERC20(comp); uint _compB = _comp.balanceOf(address(this)); if(_compB > 0){ _comp.safeTransfer(_newStrategy, _compB); } } } //Three functions covering normal leverage and deleverage situations // max is the max amount we want to increase our borrowed balance // returns the amount we actually did function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) { //we can use non-state changing because this function is always called after _calculateDesiredPosition (uint256 lent, uint256 borrowed) = getCurrentPosition(); //if we have nothing borrowed then we can't deleverage any more if (borrowed == 0 && deficit) { return 0; } (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken)); if (deficit) { amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa); } else { amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa); } emit Leverage(max, amount, deficit, address(0)); } //maxDeleverage is how much we want to reduce by function _normalDeleverage( uint256 maxDeleverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 deleveragedAmount) { uint256 theoreticalLent = 0; //collat ration should never be 0. if it is something is very wrong... but just incase if(collatRatio != 0){ theoreticalLent = borrowed.mul(1e18).div(collatRatio); } deleveragedAmount = lent.sub(theoreticalLent); if (deleveragedAmount >= borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount >= maxDeleverage) { deleveragedAmount = maxDeleverage; } uint256 exchangeRateStored = cToken.exchangeRateStored(); //redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0 //a rounding error means we need another small addition if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){ deleveragedAmount = deleveragedAmount -10; cToken.redeemUnderlying(deleveragedAmount); //our borrow has been increased by no more than maxDeleverage cToken.repayBorrow(deleveragedAmount); } } //maxDeleverage is how much we want to increase by function _normalLeverage( uint256 maxLeverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 leveragedAmount) { uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18); leveragedAmount = theoreticalBorrow.sub(borrowed); if (leveragedAmount >= maxLeverage) { leveragedAmount = maxLeverage; } if(leveragedAmount > 10){ leveragedAmount = leveragedAmount -10; cToken.borrow(leveragedAmount); cToken.mint(want.balanceOf(address(this))); } } //called by flash loan function _loanLogic( bool deficit, uint256 amount ) internal { uint256 bal = want.balanceOf(address(this)); require(bal >= amount, "FLASH_FAILED"); // to stop malicious calls //if in deficit we repay amount and then withdraw if (deficit) { cToken.repayBorrow(amount); //if we are withdrawing we take more to cover fee cToken.redeemUnderlying(amount.add(2)); } else { //check if this failed incase we borrow into liquidation require(cToken.mint(bal) == 0, "mint error"); //borrow more to cover fee // fee is so low for dydx that it does not effect our liquidation risk. //DONT USE FOR AAVE cToken.borrow(amount.add(2)); } } //emergency function that we can use to deleverage manually if something is broken function manualDeleverage(uint256 amount) external management{ require(cToken.redeemUnderlying(amount) == 0, "failed redeem"); require(cToken.repayBorrow(amount) == 0, "failed repay borrow"); } //emergency function that we can use to deleverage manually if something is broken function manualReleaseWant(uint256 amount) external onlyOwner { require(cToken.redeemUnderlying(amount) ==0, "failed redeem"); } function protectedTokens() internal override view returns (address[] memory) { //want is protected automatically address[] memory protected = new address[](0); return protected; } /****************** * Flash loan stuff ****************/ // Flash loan DXDY // amount desired is how much we are willing for position to change function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) { if(amountDesired == 0){ return 0; } uint256 amount = amountDesired; ISoloMargin solo = ISoloMargin(SOLO); // Not enough want in DyDx. So we take all we can uint256 amountInSolo = want.balanceOf(SOLO); if (amountInSolo < amount) { amount = amountInSolo; } bytes memory data = abi.encode(deficit, amount); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(dyDxMarketId, amount); operations[1] = _getCallAction( // Encode custom data for callFunction data ); operations[2] = _getDepositAction(dyDxMarketId, amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); emit Leverage(amountDesired, amount, deficit, SOLO); return amount; } //returns our current collateralisation ratio. Should be compared with collateralTarget function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); } //DyDx calls this function after doing flash loan function callFunction( address sender, Account.Info memory account, bytes memory data ) public override { (bool deficit, uint256 amount) = abi.decode(data, (bool, uint256)); require(msg.sender == SOLO, "NOT_SOLO"); require(sender == address(this)); _loanLogic(deficit, amount); } // -- Internal Helper functions -- // function _setMarketIdFromTokenAddress() internal { ISoloMargin solo = ISoloMargin(SOLO); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == address(want)) { dyDxMarketId = i; return; } } revert("No marketId found for provided token"); } modifier management(){ require(msg.sender == governance() || msg.sender == strategist, "!management"); _; } }
Flash loan DXDY amount desired is how much we are willing for position to change
function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) { if(amountDesired == 0){ return 0; } uint256 amount = amountDesired; ISoloMargin solo = ISoloMargin(SOLO); if (amountInSolo < amount) { amount = amountInSolo; } bytes memory data = abi.encode(deficit, amount); operations[0] = _getWithdrawAction(dyDxMarketId, amount); operations[1] = _getCallAction( ); operations[2] = _getDepositAction(dyDxMarketId, amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); emit Leverage(amountDesired, amount, deficit, SOLO); return amount; }
2,276,789
pragma solidity 0.4.25; interface FSForwarderInterface { function deposit() external payable returns(bool); } /// @title Contract for managing player names and affiliate payments. /// @notice This contract manages player names and affiliate payments /// from registered games. Players can buy multiple names and select /// which name to be used. Players who buy affiliate memberships can /// receive affiliate payments from registered games. /// Players can withdraw affiliate payments at any time. /// @dev The address of the forwarder is hardcoded. Check 'TODO' before /// deploy. contract FSBook { using NameFilter for string; using SafeMath for uint256; // TODO : CHECK THE ADDRESS!!! FSForwarderInterface constant private FSKingCorp = FSForwarderInterface(0x3a2321DDC991c50518969B93d2C6B76bf5309790); // data uint256 public registrationFee_ = 10 finney; // price to register a name uint256 public affiliateFee_ = 500 finney; // price to become an affiliate uint256 public pID_; // total number of players // (addr => pID) returns player id by address mapping (address => uint256) public pIDxAddr_; // (name => pID) returns player id by name mapping (bytes32 => uint256) public pIDxName_; // (pID => data) player data mapping (uint256 => Player) public plyr_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => nameNum => name) list of names a player owns mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // registered games mapping (address => bool) public registeredGames_; struct Player { address addr; bytes32 name; bool hasAff; uint256 aff; uint256 withdrawnAff; uint256 laff; uint256 affT2; uint256 names; } // constructor constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. plyr_[1].addr = 0xe0b005384df8f4d80e9a69b6210ec1929a935d97; plyr_[1].name = "sportking"; plyr_[1].hasAff = true; plyr_[1].names = 1; pIDxAddr_[0xe0b005384df8f4d80e9a69b6210ec1929a935d97] = 1; pIDxName_["sportking"] = 1; plyrNames_[1]["sportking"] = true; plyrNameList_[1][1] = "sportking"; pID_ = 1; } // modifiers /// @dev prevents contracts from interacting with fsbook modifier isHuman() { address _addr = msg.sender; require (_addr == tx.origin, "Human only"); uint256 _codeLength; assembly { _codeLength := extcodesize(_addr) } require(_codeLength == 0, "Human only"); _; } // TODO: Check address!!! /// @dev Check if caller is one of the owner(s). modifier onlyDevs() { // TODO : CHECK THE ADDRESS!!! require(msg.sender == 0xe0b005384df8f4d80e9a69b6210ec1929a935d97 || msg.sender == 0xe3ff68fb79fee1989fb67eb04e196e361ecaec3e || msg.sender == 0xb914843d2e56722a2c133eff956d1f99b820d468 || msg.sender == 0xc52FA2C9411fCd4f58be2d6725094689C46242f2, "msg sender is not a dev"); _; } /// @dev Check if caller is registered. modifier isRegisteredGame() { require(registeredGames_[msg.sender] == true, "sender is not registered"); _; } // events event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timestamp ); event onNewAffiliate ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, uint256 amountPaid, uint256 timestamp ); event onUseOldName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, uint256 timestamp ); event onGameRegistered ( address indexed gameAddress, bool enabled, uint256 timestamp ); event onWithdraw ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, uint256 amount, uint256 timestamp ); // getters: function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } // public functions: /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode) external payable isHuman() { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer); } function registerNameXaddr(string _nameString, address _affCode) external payable isHuman() { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer); } function registerNameXname(string _nameString, bytes32 _affCode) external payable isHuman() { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer); } function registerAffiliate() external payable isHuman() { // make sure name fees paid require (msg.value >= affiliateFee_, "umm..... you have to pay the name fee"); // set up address address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require (_pID > 0, "you need to be registered"); require (plyr_[_pID].hasAff == false, "already registered as affiliate"); FSKingCorp.deposit.value(msg.value)(); plyr_[_pID].hasAff = true; bytes32 _name = plyr_[_pID].name; // fire event emit onNewAffiliate(_pID, _addr, _name, msg.value, now); } function registerGame(address _contract, bool _enable) external isHuman() onlyDevs() { registeredGames_[_contract] = _enable; emit onGameRegistered(_contract, _enable, now); } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) external isHuman() { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; emit onUseOldName(_pID, _addr, _name, now); } // deposit affiliate to a code function depositAffiliate(uint256 _pID) external payable isRegisteredGame() { require(plyr_[_pID].hasAff == true, "Not registered as affiliate"); uint256 value = msg.value; plyr_[_pID].aff = value.add(plyr_[_pID].aff); } // withdraw money function withdraw() external isHuman() { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; bytes32 _name = plyr_[_pID].name; require(_pID != 0, "need to be registered"); uint256 _remainValue = (plyr_[_pID].aff).sub(plyr_[_pID].withdrawnAff); if (_remainValue > 0) { plyr_[_pID].withdrawnAff = plyr_[_pID].aff; address(msg.sender).transfer(_remainValue); } emit onWithdraw(_pID, _addr, _name, _remainValue, now); } // core logics: function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; plyr_[_pID].affT2 = _affID; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // TODO: MODIFY THIS // registration fee goes directly to community rewards //FSKingCorp.deposit.value(address(this).balance)(); FSKingCorp.deposit.value(msg.value)(); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } // external calls: function getPlayerID(address _addr) external isRegisteredGame() returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function setPlayerLAff(uint256 _pID, uint256 _lAff) external isRegisteredGame() { if (_pID != _lAff && plyr_[_pID].laff != _lAff) { plyr_[_pID].laff = _lAff; } } function getPlayerAffT2(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].affT2); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getPlayerHasAff(uint256 _pID) external view returns (bool) { return (plyr_[_pID].hasAff); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function getAffiliateFee() external view returns (uint256) { return (affiliateFee_); } function setRegistrationFee(uint256 _fee) external onlyDevs() { registrationFee_ = _fee; } function setAffiliateFee(uint256 _fee) external onlyDevs() { affiliateFee_ = _fee; } } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
make sure name fees paid set up address fire event
function registerAffiliate() external payable isHuman() { require (msg.value >= affiliateFee_, "umm..... you have to pay the name fee"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require (_pID > 0, "you need to be registered"); require (plyr_[_pID].hasAff == false, "already registered as affiliate"); FSKingCorp.deposit.value(msg.value)(); plyr_[_pID].hasAff = true; bytes32 _name = plyr_[_pID].name; emit onNewAffiliate(_pID, _addr, _name, msg.value, now); }
417,040
./partial_match/4/0x60Ae6FC8AF7e4B5b4dE2112078fDdACfb37E99aF/sources/SendMaMoney.sol
------------------------------------------------------------------------ Function to mint tokens _to The address that will receive the minted tokens. _value The amount of tokens to mint. A boolean that indicates if the operation was successful. ------------------------------------------------------------------------
function mint(address _to, uint256 _value) onlyOwner public returns (bool) { require(_to != address(0)); require(_value > 0); _totalSupply = _totalSupply.add(_value); balances[_to] = balances[_to].add(_value); emit Mint(_to, _value); emit Transfer(address(0), _to, _value); return true; }
8,745,048
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../external/FreeCollateralExternal.sol"; import "../internal/valuation/ExchangeRate.sol"; import "../internal/markets/CashGroup.sol"; import "../internal/markets/AssetRate.sol"; import "../internal/nToken/nTokenHandler.sol"; import "../internal/nToken/nTokenSupply.sol"; import "../internal/balances/TokenHandler.sol"; import "../global/LibStorage.sol"; import "../global/StorageLayoutV2.sol"; import "../global/Deployments.sol"; import "../math/SafeInt256.sol"; import "../../interfaces/notional/NotionalViews.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Views is StorageLayoutV2, NotionalViews { using CashGroup for CashGroupParameters; using TokenHandler for Token; using Market for MarketParameters; using AssetRate for AssetRateParameters; using SafeInt256 for int256; using SafeMath for uint256; using BalanceHandler for BalanceState; using nTokenHandler for nTokenPortfolio; using AccountContextHandler for AccountContext; function _checkValidCurrency(uint16 currencyId) internal view { require(0 < currencyId && currencyId <= maxCurrencyId, "Invalid currency id"); } /** Governance Parameter Getters **/ /// @notice Returns the current maximum currency id function getMaxCurrencyId() external view override returns (uint16) { return maxCurrencyId; } /// @notice Returns a currency id, a zero means that it is not listed. function getCurrencyId(address tokenAddress) external view override returns (uint16 currencyId) { currencyId = tokenAddressToCurrencyId[tokenAddress]; require(currencyId != 0, "Token not listed"); } /// @notice Returns the asset token and underlying token related to a given currency id. If underlying /// token is not set then will return the zero address function getCurrency(uint16 currencyId) external view override returns (Token memory assetToken, Token memory underlyingToken) { _checkValidCurrency(currencyId); assetToken = TokenHandler.getAssetToken(currencyId); underlyingToken = TokenHandler.getUnderlyingToken(currencyId); } /// @notice Returns the ETH and Asset rates for a currency as stored, useful for viewing how they are configured function getRateStorage(uint16 currencyId) external view override returns (ETHRateStorage memory ethRate, AssetRateStorage memory assetRate) { _checkValidCurrency(currencyId); mapping(uint256 => ETHRateStorage) storage ethStore = LibStorage.getExchangeRateStorage(); mapping(uint256 => AssetRateStorage) storage assetStore = LibStorage.getAssetRateStorage(); ethRate = ethStore[currencyId]; assetRate = assetStore[currencyId]; } /// @notice Returns a currency and its corresponding asset rate and ETH exchange rates. Note that this does not recalculate /// cToken interest rates, it only retrieves the latest stored rate. function getCurrencyAndRates(uint16 currencyId) external view override returns ( Token memory assetToken, Token memory underlyingToken, ETHRate memory ethRate, AssetRateParameters memory assetRate ) { _checkValidCurrency(currencyId); assetToken = TokenHandler.getAssetToken(currencyId); underlyingToken = TokenHandler.getUnderlyingToken(currencyId); ethRate = ExchangeRate.buildExchangeRate(currencyId); assetRate = AssetRate.buildAssetRateView(currencyId); } /// @notice Returns cash group settings for a currency function getCashGroup(uint16 currencyId) external view override returns (CashGroupSettings memory) { _checkValidCurrency(currencyId); return CashGroup.deserializeCashGroupStorage(currencyId); } /// @notice Returns the cash group along with the asset rate for convenience. function getCashGroupAndAssetRate(uint16 currencyId) external view override returns (CashGroupSettings memory cashGroup, AssetRateParameters memory assetRate) { _checkValidCurrency(currencyId); cashGroup = CashGroup.deserializeCashGroupStorage(currencyId); assetRate = AssetRate.buildAssetRateView(currencyId); } /// @notice Returns market initialization parameters for a given currency function getInitializationParameters(uint16 currencyId) external view override returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { _checkValidCurrency(currencyId); uint256 maxMarketIndex = CashGroup.getMaxMarketIndex(currencyId); (annualizedAnchorRates, proportions) = nTokenHandler.getInitializationParameters( currencyId, maxMarketIndex ); } /// @notice Returns nToken deposit parameters for a given currency function getDepositParameters(uint16 currencyId) external view override returns (int256[] memory depositShares, int256[] memory leverageThresholds) { _checkValidCurrency(currencyId); uint256 maxMarketIndex = CashGroup.getMaxMarketIndex(currencyId); (depositShares, leverageThresholds) = nTokenHandler.getDepositParameters( currencyId, maxMarketIndex ); } /// @notice Returns nToken address for a given currency function nTokenAddress(uint16 currencyId) external view override returns (address) { _checkValidCurrency(currencyId); address nToken = nTokenHandler.nTokenAddress(currencyId); require(nToken != address(0), "No nToken for currency"); return nToken; } /// @notice Returns address of the NOTE token function getNoteToken() external pure override returns (address) { return Deployments.NOTE_TOKEN_ADDRESS; } /// @notice Returns current ownership status of the contract /// @return owner is the current owner of the Notional system /// @return pendingOwner can claim ownership from the owner function getOwnershipStatus() external view override returns (address owner, address pendingOwner) { return (owner, pendingOwner); } function getGlobalTransferOperatorStatus(address operator) external view override returns (bool isAuthorized) { return globalTransferOperator[operator]; } function getAuthorizedCallbackContractStatus(address callback) external view override returns (bool isAuthorized) { return authorizedCallbackContract[callback]; } function getSecondaryIncentiveRewarder(uint16 currencyId) external view override returns (address rewarder) { address tokenAddress = nTokenHandler.nTokenAddress(currencyId); return address(nTokenHandler.getSecondaryRewarder(tokenAddress)); } /** Global System State View Methods **/ /// @notice Returns the asset settlement rate for a given maturity function getSettlementRate(uint16 currencyId, uint40 maturity) external view override returns (AssetRateParameters memory) { _checkValidCurrency(currencyId); return AssetRate.buildSettlementRateView(currencyId, maturity); } /// @notice Returns a single market function getMarket( uint16 currencyId, uint256 maturity, uint256 settlementDate ) external view override returns (MarketParameters memory) { _checkValidCurrency(currencyId); CashGroupParameters memory cashGroup = CashGroup.buildCashGroupView(currencyId); MarketParameters memory market; market.loadMarketWithSettlementDate( currencyId, maturity, block.timestamp, true, cashGroup.getRateOracleTimeWindow(), settlementDate ); return market; } /// @notice Returns all currently active markets for a currency function getActiveMarkets(uint16 currencyId) external view override returns (MarketParameters[] memory) { _checkValidCurrency(currencyId); return _getActiveMarketsAtBlockTime(currencyId, block.timestamp); } /// @notice Returns all active markets for a currency at the specified block time, useful for looking /// at historical markets function getActiveMarketsAtBlockTime(uint16 currencyId, uint32 blockTime) external view override returns (MarketParameters[] memory) { _checkValidCurrency(currencyId); return _getActiveMarketsAtBlockTime(currencyId, blockTime); } function _getActiveMarketsAtBlockTime(uint16 currencyId, uint256 blockTime) internal view returns (MarketParameters[] memory) { CashGroupParameters memory cashGroup = CashGroup.buildCashGroupView(currencyId); MarketParameters[] memory markets = new MarketParameters[](cashGroup.maxMarketIndex); for (uint256 i = 0; i < cashGroup.maxMarketIndex; i++) { cashGroup.loadMarket(markets[i], i + 1, true, blockTime); } return markets; } /// @notice Returns the current reserve balance for a currency function getReserveBalance(uint16 currencyId) external view override returns (int256 reserveBalance) { _checkValidCurrency(currencyId); // prettier-ignore ( reserveBalance, /* */, /* */, /* */ ) = BalanceHandler.getBalanceStorage(Constants.RESERVE, currencyId); } function getNTokenPortfolio(address tokenAddress) external view override returns (PortfolioAsset[] memory liquidityTokens, PortfolioAsset[] memory netfCashAssets) { // prettier-ignore ( uint16 currencyId, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = nTokenHandler.getNTokenContext(tokenAddress); liquidityTokens = PortfolioHandler.getSortedPortfolio(tokenAddress, assetArrayLength); netfCashAssets = BitmapAssetsHandler.getifCashArray( tokenAddress, currencyId, lastInitializedTime ); } function getNTokenAccount(address tokenAddress) external view override returns ( uint16 currencyId, uint256 totalSupply, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, bytes5 nTokenParameters, int256 cashBalance, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { ( currencyId, incentiveAnnualEmissionRate, lastInitializedTime, /* assetArrayLength */, nTokenParameters ) = nTokenHandler.getNTokenContext(tokenAddress); // prettier-ignore ( totalSupply, accumulatedNOTEPerNToken, lastAccumulatedTime ) = nTokenSupply.getStoredNTokenSupplyFactors(tokenAddress); // prettier-ignore ( cashBalance, /* */, /* */, /* */ ) = BalanceHandler.getBalanceStorage(tokenAddress, currencyId); } /** Account Specific View Methods **/ /// @notice Returns all account details in a single view function getAccount(address account) external view override returns ( AccountContext memory accountContext, AccountBalance[] memory accountBalances, PortfolioAsset[] memory portfolio ) { accountContext = AccountContextHandler.getAccountContext(account); accountBalances = new AccountBalance[](10); uint256 i = 0; if (accountContext.isBitmapEnabled()) { AccountBalance memory b = accountBalances[0]; b.currencyId = accountContext.bitmapCurrencyId; ( b.cashBalance, b.nTokenBalance, b.lastClaimTime, b.accountIncentiveDebt ) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId); i += 1; } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { AccountBalance memory b = accountBalances[i]; b.currencyId = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (b.currencyId == 0) break; ( b.cashBalance, b.nTokenBalance, b.lastClaimTime, b.accountIncentiveDebt ) = BalanceHandler.getBalanceStorage(account, b.currencyId); i += 1; currencies = currencies << 16; } if (accountContext.isBitmapEnabled()) { portfolio = BitmapAssetsHandler.getifCashArray( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime ); } else { portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } } /// @notice Returns account context function getAccountContext(address account) external view override returns (AccountContext memory) { return AccountContextHandler.getAccountContext(account); } /// @notice Returns account balances for a given currency function getAccountBalance(uint16 currencyId, address account) external view override returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime ) { _checkValidCurrency(currencyId); // prettier-ignore ( cashBalance, nTokenBalance, lastClaimTime, /* */ ) = BalanceHandler.getBalanceStorage(account, currencyId); } /// @notice Returns account portfolio of assets function getAccountPortfolio(address account) external view override returns (PortfolioAsset[] memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.isBitmapEnabled()) { return BitmapAssetsHandler.getifCashArray( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime ); } else { return PortfolioHandler.getSortedPortfolio(account, accountContext.assetArrayLength); } } /// @notice Returns the fCash amount at the specified maturity for a bitmapped portfolio function getfCashNotional( address account, uint16 currencyId, uint256 maturity ) external view override returns (int256) { _checkValidCurrency(currencyId); return BitmapAssetsHandler.getifCashNotional(account, currencyId, maturity); } /// @notice Returns the assets bitmap for an account function getAssetsBitmap(address account, uint16 currencyId) external view override returns (bytes32) { _checkValidCurrency(currencyId); return BitmapAssetsHandler.getAssetsBitmap(account, currencyId); } /// @notice Returns free collateral of an account along with an array of the individual net available /// asset cash amounts function getFreeCollateral(address account) external view override returns (int256, int256[] memory) { return FreeCollateralExternal.getFreeCollateralView(account); } /// @notice Returns the current treasury manager contract function getTreasuryManager() external view override returns (address) { return treasuryManagerContract; } /// @notice Returns the current reserve buffer for a currency /// @param currencyId refers to the currency of the reserve function getReserveBuffer(uint16 currencyId) external view override returns (uint256) { return reserveBuffer[currencyId]; } /// @notice Get a list of deployed library addresses (sorted by library name) function getLibInfo() external view returns (address, address) { return (address(FreeCollateralExternal), address(MigrateIncentives)); } /// @notice Returns the lending pool address function getLendingPool() external view override returns (address) { return address(LibStorage.getLendingPool().lendingPool); } fallback() external { revert("Method not found"); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../external/SettleAssetsExternal.sol"; import "../internal/AccountContextHandler.sol"; import "../internal/valuation/FreeCollateral.sol"; /// @title Externally deployed library for free collateral calculations library FreeCollateralExternal { using AccountContextHandler for AccountContext; /// @notice Returns the ETH denominated free collateral of an account, represents the amount of /// debt that the account can incur before liquidation. If an account's assets need to be settled this /// will revert, either settle the account or use the off chain SDK to calculate free collateral. /// @dev Called via the Views.sol method to return an account's free collateral. Does not work /// for the nToken, the nToken does not have an account context. /// @param account account to calculate free collateral for /// @return total free collateral in ETH w/ 8 decimal places /// @return array of net local values in asset values ordered by currency id function getFreeCollateralView(address account) external view returns (int256, int256[] memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); // The internal free collateral function does not account for settled assets. The Notional SDK // can calculate the free collateral off chain if required at this point. require(!accountContext.mustSettleAssets(), "Assets not settled"); return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp); } /// @notice Calculates free collateral and will revert if it falls below zero. If the account context /// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets /// need to be settled first. /// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be /// called before the end of any transaction for accounts where FC can decrease. /// @param account account to calculate free collateral for function checkFreeCollateralAndRevert(address account) external { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); require(!accountContext.mustSettleAssets(), "Assets not settled"); (int256 ethDenominatedFC, bool updateContext) = FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp); if (updateContext) { accountContext.setAccountContext(account); } require(ethDenominatedFC >= 0, "Insufficient free collateral"); } /// @notice Calculates liquidation factors for an account /// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is /// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then /// liquidation actions will revert. /// @dev an ntoken account will return 0 FC and revert if called /// @param account account to liquidate /// @param localCurrencyId currency that the debts are denominated in /// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation /// @return accountContext the accountContext of the liquidated account /// @return factors struct of relevant factors for liquidation /// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array) function getLiquidationFactors( address account, uint256 localCurrencyId, uint256 collateralCurrencyId ) external returns ( AccountContext memory accountContext, LiquidationFactors memory factors, PortfolioAsset[] memory portfolio ) { accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { accountContext = SettleAssetsExternal.settleAccount(account, accountContext); } if (accountContext.isBitmapEnabled()) { // A bitmap currency can only ever hold debt in this currency require(localCurrencyId == accountContext.bitmapCurrencyId); } (factors, portfolio) = FreeCollateral.getLiquidationFactors( account, accountContext, block.timestamp, localCurrencyId, collateralCurrencyId ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../balances/TokenHandler.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol"; library ExchangeRate { using SafeInt256 for int256; /// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are /// always applied in this method. /// @param er exchange rate object from base to ETH /// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) { int256 multiplier = balance > 0 ? er.haircut : er.buffer; // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals) // Therefore the result is in ethDecimals int256 result = balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div( er.rateDecimals ); return result; } /// @notice Converts the balance denominated in ETH to the equivalent value in a base currency. /// Buffers and haircuts ARE NOT applied in this method. /// @param er exchange rate object from base to ETH /// @param balance amount (denominated in ETH) to convert function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) { // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals / rateDecimals int256 result = balance.mul(er.rateDecimals).div(er.rate); return result; } /// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in /// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals /// @param baseER base exchange rate struct /// @param quoteER quote exchange rate struct function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER) internal pure returns (int256) { return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate); } /// @notice Returns an ETHRate object used to calculate free collateral function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) { mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage(); ETHRateStorage storage ethStorage = store[currencyId]; int256 rateDecimals; int256 rate; if (currencyId == Constants.ETH_CURRENCY_ID) { // ETH rates will just be 1e18, but will still have buffers, haircuts, // and liquidation discounts rateDecimals = Constants.ETH_DECIMALS; rate = Constants.ETH_DECIMALS; } else { // prettier-ignore ( /* roundId */, rate, /* uint256 startedAt */, /* updatedAt */, /* answeredInRound */ ) = ethStorage.rateOracle.latestRoundData(); require(rate > 0, "Invalid rate"); // No overflow, restricted on storage rateDecimals = int256(10**ethStorage.rateDecimalPlaces); if (ethStorage.mustInvert) { rate = rateDecimals.mul(rateDecimals).div(rate); } } return ETHRate({ rateDecimals: rateDecimals, rate: rate, buffer: ethStorage.buffer, haircut: ethStorage.haircut, liquidationDiscount: ethStorage.liquidationDiscount }); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Market.sol"; import "./AssetRate.sol"; import "./DateTime.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library CashGroup { using SafeMath for uint256; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; // Bit number references for each parameter in the 32 byte word (0-indexed) uint256 private constant MARKET_INDEX_BIT = 31; uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30; uint256 private constant TOTAL_FEE_BIT = 29; uint256 private constant RESERVE_FEE_SHARE_BIT = 28; uint256 private constant DEBT_BUFFER_BIT = 27; uint256 private constant FCASH_HAIRCUT_BIT = 26; uint256 private constant SETTLEMENT_PENALTY_BIT = 25; uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24; uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23; // 7 bytes allocated, one byte per market for the liquidity token haircut uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22; // 7 bytes allocated, one byte per market for the rate scalar uint256 private constant RATE_SCALAR_FIRST_BIT = 15; // Offsets for the bytes of the different parameters uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8; uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8; uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8; uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8; uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8; uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8; uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8; uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8; uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8; uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8; uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8; /// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies /// the ln() portion of the liquidity curve as an inverse so it increases with time to /// maturity. The effect of the rate scalar on slippage must decrease with time to maturity. function getRateScalar( CashGroupParameters memory cashGroup, uint256 marketIndex, uint256 timeToMaturity ) internal pure returns (int256) { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1); int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION; int256 rateScalar = scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity)); // Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the // division above. require(rateScalar > 0); // dev: rate scalar underflow return rateScalar; } /// @notice Haircut on liquidity tokens to account for the risk associated with changes in the /// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100. function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType) internal pure returns (uint8) { require( Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX ); // dev: liquidity haircut invalid asset type uint256 offset = LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX); return uint8(uint256(cashGroup.data >> offset)); } /// @notice Total trading fee denominated in RATE_PRECISION with basis point increments function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT; } /// @notice Percentage of the total trading fee that goes to the reserve function getReserveFeeShare(CashGroupParameters memory cashGroup) internal pure returns (int256) { return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE)); } /// @notice fCash haircut for valuation denominated in rate precision with five basis point increments function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } /// @notice Time window factor for the rate oracle denominated in seconds with five minute increments. function getRateOracleTimeWindow(CashGroupParameters memory cashGroup) internal pure returns (uint256) { // This is denominated in 5 minute increments in storage return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES; } /// @notice Penalty rate for settling cash debts denominated in basis points function getSettlementPenalty(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for positive fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for negative fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } function loadMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 marketIndex, bool needsLiquidity, uint256 blockTime ) internal view { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market"); uint256 maturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex)); market.loadMarket( cashGroup.currencyId, maturity, blockTime, needsLiquidity, getRateOracleTimeWindow(cashGroup) ); } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity ) internal pure returns (uint256) { require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) // NOTE: this subtraction should never overflow, the linear interpolation between two points above zero // cannot go below zero return shortRate.sub( // This is reversed to keep it it positive (shortRate - longRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) ); } } /// @dev Gets an oracle rate given any valid maturity. function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); } else { uint256 referenceTime = DateTime.getReferenceTime(blockTime); // DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { // In this case the short market is the annualized asset supply rate shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); } else { // Minimum value for marketIndex here is 2 shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } } function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) { mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); return store[currencyId]; } /// @dev Helper method for validating maturities in ERC1155Action function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) { bytes32 data = _getCashGroupStorageBytes(currencyId); return uint8(data[MARKET_INDEX_BIT]); } /// @notice Checks all cash group settings for invalid values and sets them into storage function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal { // Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market. // The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month // fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash // groups with 0 market index, it has no effect. require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: invalid market index" ); require( cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS, "CG: invalid reserve share" ); require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex); require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex); // This is required so that fCash liquidation can proceed correctly require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS); require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS); // Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId); require( previousMaxMarketIndex <= cashGroup.maxMarketIndex, "CG: market index cannot decrease" ); // Per cash group settings bytes32 data = (bytes32(uint256(cashGroup.maxMarketIndex)) | (bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) | (bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) | (bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) | (bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) | (bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) | (bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) << LIQUIDATION_FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER)); // Per market group settings for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) { require( cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS, "CG: invalid token haircut" ); data = data | (bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) << (LIQUIDITY_TOKEN_HAIRCUT + i * 8)); } for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) { // Causes a divide by zero error require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar"); data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8)); } mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); store[currencyId] = data; } /// @notice Deserialize the cash group storage bytes into a user friendly object function deserializeCashGroupStorage(uint256 currencyId) internal view returns (CashGroupSettings memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex)); uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex)); for (uint8 i = 0; i < maxMarketIndex; i++) { tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]); rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]); } return CashGroupSettings({ maxMarketIndex: maxMarketIndex, rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]), totalFeeBPS: uint8(data[TOTAL_FEE_BIT]), reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]), debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]), fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]), settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]), liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]), liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]), liquidityTokenHaircuts: tokenHaircuts, rateScalars: rateScalars }); } function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate) private view returns (CashGroupParameters memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); return CashGroupParameters({ currencyId: currencyId, maxMarketIndex: maxMarketIndex, assetRate: assetRate, data: data }); } /// @notice Builds a cash group using a view version of the asset rate function buildCashGroupView(uint16 currencyId) internal view returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId); return _buildCashGroup(currencyId, assetRate); } /// @notice Builds a cash group using a stateful version of the asset rate function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId); return _buildCashGroup(currencyId, assetRate); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/notional/AssetRateAdapter.sol"; library AssetRate { using SafeInt256 for int256; event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); // Asset rates are in 1e18 decimals (cToken exchange rates), internal balances // are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10 int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10; /// @notice Converts an internal asset cash value to its underlying token value. /// @param ar exchange rate object between asset and underlying /// @param assetBalance amount to convert to underlying function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256) { // Calculation here represents: // rate * balance * internalPrecision / rateDecimals * underlyingPrecision int256 underlyingBalance = ar.rate .mul(assetBalance) .div(ASSET_RATE_DECIMAL_DIFFERENCE) .div(ar.underlyingDecimals); return underlyingBalance; } /// @notice Converts an internal underlying cash value to its asset cash value /// @param ar exchange rate object between asset and underlying /// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance) internal pure returns (int256) { // Calculation here represents: // rateDecimals * balance * underlyingPrecision / rate * internalPrecision int256 assetBalance = underlyingBalance .mul(ASSET_RATE_DECIMAL_DIFFERENCE) .mul(ar.underlyingDecimals) .div(ar.rate); return assetBalance; } /// @notice Returns the current per block supply rate, is used when calculating oracle rates /// for idiosyncratic fCash with a shorter duration than the 3 month maturity. function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) { // If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero. if (address(ar.rateOracle) == address(0)) return 0; uint256 rate = ar.rateOracle.getAnnualizedSupplyRate(); // Zero supply rate is valid since this is an interest rate, we do not divide by // the supply rate so we do not get div by zero errors. require(rate >= 0); // dev: invalid supply rate return rate; } function _getAssetRateStorage(uint256 currencyId) private view returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) { mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); AssetRateStorage storage ar = store[currencyId]; rateOracle = AssetRateAdapter(ar.rateOracle); underlyingDecimalPlaces = ar.underlyingDecimalPlaces; } /// @notice Gets an asset rate using a view function, does not accrue interest so the /// exchange rate will not be up to date. Should only be used for non-stateful methods function _getAssetRateView(uint256 currencyId) private view returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateView(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Gets an asset rate using a stateful function, accrues interest so the /// exchange rate will be up to date for the current block. function _getAssetRateStateful(uint256 currencyId) private returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateStateful(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Returns an asset rate object using the view method function buildAssetRateView(uint256 currencyId) internal view returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateView(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @notice Returns an asset rate object using the stateful method function buildAssetRateStateful(uint256 currencyId) internal returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStateful(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @dev Gets a settlement rate object function _getSettlementRateStorage(uint256 currencyId, uint256 maturity) private view returns ( int256 settlementRate, uint8 underlyingDecimalPlaces ) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); SettlementRateStorage storage rateStorage = store[currencyId][maturity]; settlementRate = rateStorage.settlementRate; underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces; } /// @notice Returns a settlement rate object using the view method function buildSettlementRateView(uint256 currencyId, uint256 maturity) internal view returns (AssetRateParameters memory) { // prettier-ignore ( int256 settlementRate, uint8 underlyingDecimalPlaces ) = _getSettlementRateStorage(currencyId, maturity); // Asset exchange rates cannot be zero if (settlementRate == 0) { // If settlement rate has not been set then we need to fetch it // prettier-ignore ( settlementRate, /* address */, underlyingDecimalPlaces ) = _getAssetRateView(currencyId); } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } /// @notice Returns a settlement rate object and sets the rate if it has not been set yet function buildSettlementRateStateful( uint256 currencyId, uint256 maturity, uint256 blockTime ) internal returns (AssetRateParameters memory) { (int256 settlementRate, uint8 underlyingDecimalPlaces) = _getSettlementRateStorage(currencyId, maturity); if (settlementRate == 0) { // Settlement rate has not yet been set, set it in this branch AssetRateAdapter rateOracle; // If rate oracle == 0 then this will return the identity settlement rate // prettier-ignore ( settlementRate, rateOracle, underlyingDecimalPlaces ) = _getAssetRateStateful(currencyId); if (address(rateOracle) != address(0)) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); // Only need to set settlement rates when the rate oracle is set (meaning the asset token has // a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1 // rate since they are the same. require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow SettlementRateStorage storage rateStorage = store[currencyId][maturity]; rateStorage.blockTime = uint40(blockTime); rateStorage.settlementRate = uint128(settlementRate); rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces; emit SetSettlementRate(currencyId, maturity, uint128(settlementRate)); } } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenSupply.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenHandler { using SafeInt256 for int256; /// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning /// two constants to each other. uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @notice Returns an account context object that is specific to nTokens. function getNTokenContext(address tokenAddress) internal view returns ( uint16 currencyId, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters; } /// @notice Returns the nToken token address for a given currency function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) { mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage(); return store[currencyId]; } /// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be /// reset once this is set. function setNTokenAddress(uint16 currencyId, address tokenAddress) internal { mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage(); require(addressStore[currencyId] == address(0), "PT: token address exists"); mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage(); nTokenContext storage context = contextStore[tokenAddress]; require(context.currencyId == 0, "PT: currency exists"); // This will initialize all other context slots to zero context.currencyId = currencyId; addressStore[currencyId] = tokenAddress; } /// @notice Set nToken token collateral parameters function setNTokenCollateralParameters( address tokenAddress, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut"); // The pv haircut percentage must be less than the liquidation percentage or else liquidators will not // get profit for liquidating nToken. require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut"); // Ensure that the cash withholding buffer is greater than the residual purchase incentive or // the nToken may not have enough cash to pay accounts to buy its negative ifCash require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts"); bytes5 parameters = (bytes5(uint40(residualPurchaseIncentive10BPS)) | (bytes5(uint40(pvHaircutPercentage)) << 8) | (bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) | (bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) | (bytes5(uint40(liquidationHaircutPercentage)) << 32)); // Set the parameters context.nTokenParameters = parameters; } /// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different /// contract, aside from the native NOTE token incentives. function setSecondaryRewarder( uint16 currencyId, IRewarder rewarder ) internal { address tokenAddress = nTokenAddress(currencyId); // nToken must exist for a secondary rewarder require(tokenAddress != address(0)); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; // Setting the rewarder to address(0) will disable it. We use a context setting here so that // we can save a storage read before getting the rewarder context.hasSecondaryRewarder = (address(rewarder) != address(0)); LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder; } /// @notice Returns the secondary rewarder if it is set function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; if (context.hasSecondaryRewarder) { return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress]; } else { return IRewarder(address(0)); } } function setArrayLengthAndInitializedTime( address tokenAddress, uint8 arrayLength, uint256 lastInitializedTime ) internal { require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.lastInitializedTime = uint32(lastInitializedTime); context.assetArrayLength = arrayLength; } /// @notice Returns the array of deposit shares and leverage thresholds for nTokens function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory depositShares, int256[] memory leverageThresholds) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; (depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false); } /// @notice Sets the deposit parameters /// @dev We pack the values in alternating between the two parameters into either one or two // storage slots depending on the number of markets. This is to save storage reads when we use the parameters. function setDepositParameters( uint256 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) internal { require( depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: deposit share length" ); require(depositShares.length == leverageThresholds.length, "PT: leverage share length"); uint256 shareSum; for (uint256 i; i < depositShares.length; i++) { // This cannot overflow in uint 256 with 9 max slots shareSum = shareSum + depositShares[i]; require( leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION, "PT: leverage threshold" ); } // Total deposit share must add up to 100% require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum"); mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; _setParameters(depositParameters, depositShares, leverageThresholds); } /// @notice Sets the initialization parameters for the markets, these are read only when markets /// are initialized function setInitializationParameters( uint256 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) internal { require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length"); require(proportions.length == annualizedAnchorRates.length, "PT: proportions length"); for (uint256 i; i < proportions.length; i++) { // Proportions must be between zero and the rate precision require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero"); require( proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION, "PT: invalid proportion" ); } mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; _setParameters(initParameters, annualizedAnchorRates, proportions); } /// @notice Returns the array of initialization parameters for a given currency. function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; (annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true); } function _getParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint256 maxMarketIndex, bool noUnset ) private view returns (int256[] memory, int256[] memory) { uint256 index = 0; int256[] memory array1 = new int256[](maxMarketIndex); int256[] memory array2 = new int256[](maxMarketIndex); for (uint256 i; i < maxMarketIndex; i++) { array1[i] = slot[index]; index++; array2[i] = slot[index]; index++; if (noUnset) { require(array1[i] > 0 && array2[i] > 0, "PT: init value zero"); } } return (array1, array2); } function _setParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint32[] calldata array1, uint32[] calldata array2 ) private { uint256 index = 0; for (uint256 i = 0; i < array1.length; i++) { slot[index] = array1[i]; index++; slot[index] = array2[i]; index++; } } function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); // prettier-ignore ( uint256 totalSupply, /* accumulatedNOTEPerNToken */, /* lastAccumulatedTime */ ) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); // prettier-ignore ( nToken.cashBalance, /* nTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId); } /// @notice Uses buildCashGroupStateful function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId) internal { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId); } /// @notice Uses buildCashGroupView function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId) internal view { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupView(currencyId); } /// @notice Returns the next settle time for the nToken which is 1 quarter away function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) { if (nToken.lastInitializedTime == 0) return 0; return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenSupply { using SafeInt256 for int256; using SafeMath for uint256; /// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating /// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead. function getStoredNTokenSupplyFactors(address tokenAddress) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; totalSupply = nTokenStorage.totalSupply; // NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken // must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken; lastAccumulatedTime = nTokenStorage.lastAccumulatedTime; } /// @notice Returns the updated accumulated NOTE per nToken for calculating incentives function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { ( totalSupply, accumulatedNOTEPerNToken, lastAccumulatedTime ) = getStoredNTokenSupplyFactors(tokenAddress); // nToken totalSupply is never allowed to drop to zero but we check this here to avoid // divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not // zero to avoid a massive accumulation amount on initialization. if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) { // prettier-ignore ( /* currencyId */, uint256 emissionRatePerYear, /* initializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(tokenAddress); uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE( // Emission rate is denominated in whole tokens, scale to 1e8 decimals here emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)), // Time since last accumulation (overflow checked above) blockTime - lastAccumulatedTime, totalSupply ); accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken); require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow } } /// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision function _calculateAdditionalNOTE( uint256 emissionRatePerYear, uint256 timeSinceLastAccumulation, uint256 totalSupply ) private pure returns (uint256) { // If we use 18 decimal places as the accumulation precision then we will overflow uint128 when // a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max // NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe // using 18 decimal places and uint128 storage slot // timeSinceLastAccumulation (SECONDS) // accumulatedNOTEPerSharePrecision (1e18) // emissionRatePerYear (INTERNAL_TOKEN_PRECISION) // DIVIDE BY // YEAR (SECONDS) // totalSupply (INTERNAL_TOKEN_PRECISION) return timeSinceLastAccumulation .mul(Constants.INCENTIVE_ACCUMULATION_PRECISION) .mul(emissionRatePerYear) .div(Constants.YEAR) // totalSupply > 0 is checked in the calling function .div(totalSupply); } /// @notice Updates the nToken token supply amount when minting or redeeming. /// @param tokenAddress address of the nToken /// @param netChange positive or negative change to the total nToken supply /// @param blockTime current block time /// @return accumulatedNOTEPerNToken updated to the given block time function changeNTokenSupply( address tokenAddress, int256 netChange, uint256 blockTime ) internal returns (uint256) { ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, /* uint256 lastAccumulatedTime */ ) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime); // Update storage variables mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; int256 newTotalSupply = int256(totalSupply).add(netChange); // We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to // exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check. require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow nTokenStorage.totalSupply = uint96(newTotalSupply); // NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what // the user would see if querying the view function nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken); require(blockTime < type(uint32).max); // dev: block time overflow nTokenStorage.lastAccumulatedTime = uint32(blockTime); return accumulatedNOTEPerNToken; } /// @notice Called by governance to set the new emission rate function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal { // Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the // emission rate changeNTokenSupply(tokenAddress, 0, blockTime); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.incentiveAnnualEmissionRate = newEmissionsRate; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../global/Deployments.sol"; import "./protocols/AaveHandler.sol"; import "./protocols/CompoundHandler.sol"; import "./protocols/GenericToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @notice Handles all external token transfers and events library TokenHandler { using SafeInt256 for int256; using SafeMath for uint256; function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][false]; tokenStorage.maxCollateralBalance = maxCollateralBalance; } function getAssetToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, false); } function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, true); } /// @notice Gets token data for a particular currency id, if underlying is set to true then returns /// the underlying token. (These may not always exist) function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][underlying]; return Token({ tokenAddress: tokenStorage.tokenAddress, hasTransferFee: tokenStorage.hasTransferFee, // No overflow, restricted on storage decimals: int256(10**tokenStorage.decimalPlaces), tokenType: tokenStorage.tokenType, maxCollateralBalance: tokenStorage.maxCollateralBalance }); } /// @notice Sets a token for a currency id. function setToken( uint256 currencyId, bool underlying, TokenStorage memory tokenStorage ) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) { // Hardcoded parameters for ETH just to make sure we don't get it wrong. TokenStorage storage ts = store[currencyId][true]; ts.tokenAddress = address(0); ts.hasTransferFee = false; ts.tokenType = TokenType.Ether; ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES; ts.maxCollateralBalance = 0; return; } // Check token address require(tokenStorage.tokenAddress != address(0), "TH: address is zero"); // Once a token is set we cannot override it. In the case that we do need to do change a token address // then we should explicitly upgrade this method to allow for a token to be changed. Token memory token = _getToken(currencyId, underlying); require( token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0), "TH: token cannot be reset" ); require(0 < tokenStorage.decimalPlaces && tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals"); // Validate token type require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once if (underlying) { // Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily // during mint and redeem actions. require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent } else { require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent } if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) { // Set the approval for the underlying so that we can mint cTokens or aTokens Token memory underlyingToken = getUnderlyingToken(currencyId); // cTokens call transfer from the tokenAddress, but aTokens use the LendingPool // to initiate all transfers address approvalAddress = tokenStorage.tokenType == TokenType.cToken ? tokenStorage.tokenAddress : address(LibStorage.getLendingPool().lendingPool); // ERC20 tokens should return true on success for an approval, but Tether // does not return a value here so we use the NonStandard interface here to // check that the approval was successful. IEIP20NonStandard(underlyingToken.tokenAddress).approve( approvalAddress, type(uint256).max ); GenericToken.checkReturnCode(); } store[currencyId][underlying] = tokenStorage; } /** * @notice If a token is mintable then will mint it. At this point we expect to have the underlying * balance in the contract already. * @param assetToken the asset token to mint * @param underlyingAmountExternal the amount of underlying to transfer to the mintable token * @return the amount of asset tokens minted, will always be a positive integer */ function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) { // aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this // value in internal accounting since it will not allow individual users to accrue aToken interest. Use the // scaledBalanceOf function call instead for internal accounting. bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); if (assetToken.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); AaveHandler.mint(underlyingToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { CompoundHandler.mint(assetToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cETH) { CompoundHandler.mintCETH(assetToken); } else { revert(); // dev: non mintable token } uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); // This is the starting and ending balance in external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } /** * @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance * to the account * @param assetToken asset token to redeem * @param currencyId the currency id of the token * @param account account to transfer the underlying to * @param assetAmountExternal the amount to transfer in asset token denomination and external precision * @return the actual amount of underlying tokens transferred. this is used as a return value back to the * user, is not used for internal accounting purposes */ function redeem( Token memory assetToken, uint256 currencyId, address account, uint256 assetAmountExternal ) internal returns (int256) { uint256 transferAmount; if (assetToken.tokenType == TokenType.cETH) { transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal); } else { Token memory underlyingToken = getUnderlyingToken(currencyId); if (assetToken.tokenType == TokenType.aToken) { transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal); } else { revert(); // dev: non redeemable token } } // Use the negative value here to signify that assets have left the protocol return SafeInt256.toInt(transferAmount).neg(); } /// @notice Handles transfers into and out of the system denominated in the external token decimal /// precision. function transfer( Token memory token, address account, uint256 currencyId, int256 netTransferExternal ) internal returns (int256 actualTransferExternal) { // This will be true in all cases except for deposits where the token has transfer fees. For // aTokens this value is set before convert from scaled balances to principal plus interest actualTransferExternal = netTransferExternal; if (token.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); // aTokens need to be converted when we handle the transfer since the external balance format // is not the same as the internal balance format that we use netTransferExternal = AaveHandler.convertFromScaledBalanceExternal( underlyingToken.tokenAddress, netTransferExternal ); } if (netTransferExternal > 0) { // Deposits must account for transfer fees. int256 netDeposit = _deposit(token, account, uint256(netTransferExternal)); // If an aToken has a transfer fee this will still return a balance figure // in scaledBalanceOf terms due to the selector if (token.hasTransferFee) actualTransferExternal = netDeposit; } else if (token.tokenType == TokenType.Ether) { // netTransferExternal can only be negative or zero at this point GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg())); } else { GenericToken.safeTransferOut( token.tokenAddress, account, // netTransferExternal is zero or negative here uint256(netTransferExternal.neg()) ); } } /// @notice Handles token deposits into Notional. If there is a transfer fee then we must /// calculate the net balance after transfer. Amounts are denominated in the destination token's /// precision. function _deposit( Token memory token, address account, uint256 amount ) private returns (int256) { uint256 startingBalance; uint256 endingBalance; bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; if (token.hasTransferFee) { startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } GenericToken.safeTransferIn(token.tokenAddress, account, amount); if (token.hasTransferFee || token.maxCollateralBalance > 0) { // If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably // the correct behavior because if collateral accrues interest over time we should not somehow go over the // maxCollateralBalance due to the passage of time. endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } if (token.maxCollateralBalance > 0) { int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance)); // Max collateral balance is stored as uint72, no overflow require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance } // Math is done in uint inside these statements and will revert on negative if (token.hasTransferFee) { return SafeInt256.toInt(endingBalance.sub(startingBalance)); } else { return SafeInt256.toInt(amount); } } function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) { // If token decimals > INTERNAL_TOKEN_PRECISION: // on deposit: resulting dust will accumulate to protocol // on withdraw: protocol may lose dust amount. However, withdraws are only calculated based // on a conversion from internal token precision to external token precision so therefore dust // amounts cannot be specified for withdraws. // If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the // end of amount and will not result in dust. if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals); } function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) { if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; // If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount // by adding a number of zeros to the end and will not result in dust. // If token decimals < INTERNAL_TOKEN_PRECISION: // on deposit: Deposits are specified in external token precision and there is no loss of precision when // tokens are converted from external to internal precision // on withdraw: this calculation will round down such that the protocol retains the residual cash balance return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION); } function transferIncentive(address account, uint256 tokensToTransfer) internal { GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; import "./Constants.sol"; import "../../interfaces/notional/IRewarder.sol"; import "../../interfaces/aave/ILendingPool.sol"; library LibStorage { /// @dev Offset for the initial slot in lib storage, gives us this number of storage slots /// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it. uint256 private constant STORAGE_SLOT_BASE = 1000000; /// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX /// in practice. It is possible to exceed that value during liquidation up to 14 potential assets. uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @dev Storage IDs for storage buckets. Each id maps to an internal storage /// slot used for a particular mapping /// WARNING: APPEND ONLY enum StorageId { Unused, AccountStorage, nTokenContext, nTokenAddress, nTokenDeposit, nTokenInitialization, Balance, Token, SettlementRate, CashGroup, Market, AssetsBitmap, ifCashBitmap, PortfolioArray, // WARNING: this nTokenTotalSupply storage object was used for a buggy version // of the incentives calculation. It should only be used for accounts who have // not claimed before the migration nTokenTotalSupply_deprecated, AssetRate, ExchangeRate, nTokenTotalSupply, SecondaryIncentiveRewarder, LendingPool } /// @dev Mapping from an account address to account context function getAccountStorage() internal pure returns (mapping(address => AccountContext) storage store) { uint256 slot = _getStorageSlot(StorageId.AccountStorage); assembly { store.slot := slot } } /// @dev Mapping from an nToken address to nTokenContext function getNTokenContextStorage() internal pure returns (mapping(address => nTokenContext) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenContext); assembly { store.slot := slot } } /// @dev Mapping from currency id to nTokenAddress function getNTokenAddressStorage() internal pure returns (mapping(uint256 => address) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenAddress); assembly { store.slot := slot } } /// @dev Mapping from currency id to uint32 fixed length array of /// deposit factors. Deposit shares and leverage thresholds are stored striped to /// reduce the number of storage reads. function getNTokenDepositStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenDeposit); assembly { store.slot := slot } } /// @dev Mapping from currency id to fixed length array of initialization factors, /// stored striped like deposit shares. function getNTokenInitStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenInitialization); assembly { store.slot := slot } } /// @dev Mapping from account to currencyId to it's balance storage for that currency function getBalanceStorage() internal pure returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Balance); assembly { store.slot := slot } } /// @dev Mapping from currency id to a boolean for underlying or asset token to /// the TokenStorage function getTokenStorage() internal pure returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Token); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its corresponding SettlementRate function getSettlementRateStorage() internal pure returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.SettlementRate); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its tightly packed cash group parameters function getCashGroupStorage() internal pure returns (mapping(uint256 => bytes32) storage store) { uint256 slot = _getStorageSlot(StorageId.CashGroup); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to settlement date for a market function getMarketStorage() internal pure returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.Market); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its assets bitmap function getAssetsBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => bytes32)) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetsBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance function getifCashBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.ifCashBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to its fixed length array of portfolio assets function getPortfolioArrayStorage() internal pure returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store) { uint256 slot = _getStorageSlot(StorageId.PortfolioArray); assembly { store.slot := slot } } function getDeprecatedNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated); assembly { store.slot := slot } } /// @dev Mapping from nToken address to its total supply values function getNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and asset for trading /// and free collateral. Mapping is from currency id to rate storage object. function getAssetRateStorage() internal pure returns (mapping(uint256 => AssetRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetRate); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and ETH for free /// collateral purposes. Mapping is from currency id to rate storage object. function getExchangeRateStorage() internal pure returns (mapping(uint256 => ETHRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.ExchangeRate); assembly { store.slot := slot } } /// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists function getSecondaryIncentiveRewarder() internal pure returns (mapping(address => IRewarder) storage store) { uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder); assembly { store.slot := slot } } /// @dev Returns the address of the lending pool function getLendingPool() internal pure returns (LendingPoolStorage storage store) { uint256 slot = _getStorageSlot(StorageId.LendingPool); assembly { store.slot := slot } } /// @dev Get the storage slot given a storage ID. /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function _getStorageSlot(StorageId storageId) private pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return uint256(storageId) + STORAGE_SLOT_BASE; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./StorageLayoutV1.sol"; contract StorageLayoutV2 is StorageLayoutV1 { // Contract that manages the treasury and reserves address internal treasuryManagerContract; // Reserve buffers per currency, used in the TreasuryAction contract mapping(uint256 => uint256) internal reserveBuffer; // Pending owner used in the transfer ownership / claim ownership pattern address internal pendingOwner; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce /// gas costs for immutable addresses. They must be updated per environment that Notional /// is deployed to. library Deployments { address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../global/Constants.sol"; library SafeInt256 { int256 private constant _INT256_MIN = type(int256).min; /// @dev Returns the multiplication of two signed integers, reverting on /// overflow. /// Counterpart to Solidity's `*` operator. /// Requirements: /// - Multiplication cannot overflow. function mul(int256 a, int256 b) internal pure returns (int256 c) { c = a * b; if (a == -1) require (b == 0 || c / b == a); else require (a == 0 || c / a == b); } /// @dev Returns the integer division of two signed integers. Reverts on /// division by zero. The result is rounded towards zero. /// Counterpart to Solidity's `/` operator. Note: this function uses a /// `revert` opcode (which leaves remaining gas untouched) while Solidity /// uses an invalid opcode to revert (consuming all remaining gas). /// Requirements: /// - The divisor cannot be zero. function div(int256 a, int256 b) internal pure returns (int256 c) { require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow // NOTE: solidity will automatically revert on divide by zero c = a / b; } function sub(int256 x, int256 y) internal pure returns (int256 z) { // taken from uniswap v3 require((z = x - y) <= x == (y >= 0)); } function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } function neg(int256 x) internal pure returns (int256 y) { return mul(-1, x); } function abs(int256 x) internal pure returns (int256) { if (x < 0) return neg(x); else return x; } function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) { z = sub(x, y); require(z >= 0); // dev: int256 sub to negative return z; } /// @dev Calculates x * RATE_PRECISION / y while checking overflows function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, Constants.RATE_PRECISION), y); } /// @dev Calculates x * y / RATE_PRECISION while checking overflows function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, y), Constants.RATE_PRECISION); } function toUint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function toInt(uint256 x) internal pure returns (int256) { require (x <= uint256(type(int256).max)); // dev: toInt overflow return int256(x); } function max(int256 x, int256 y) internal pure returns (int256) { return x > y ? x : y; } function min(int256 x, int256 y) internal pure returns (int256) { return x < y ? x : y; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../contracts/global/Types.sol"; interface NotionalViews { function getMaxCurrencyId() external view returns (uint16); function getCurrencyId(address tokenAddress) external view returns (uint16 currencyId); function getCurrency(uint16 currencyId) external view returns (Token memory assetToken, Token memory underlyingToken); function getRateStorage(uint16 currencyId) external view returns (ETHRateStorage memory ethRate, AssetRateStorage memory assetRate); function getCurrencyAndRates(uint16 currencyId) external view returns ( Token memory assetToken, Token memory underlyingToken, ETHRate memory ethRate, AssetRateParameters memory assetRate ); function getCashGroup(uint16 currencyId) external view returns (CashGroupSettings memory); function getCashGroupAndAssetRate(uint16 currencyId) external view returns (CashGroupSettings memory cashGroup, AssetRateParameters memory assetRate); function getInitializationParameters(uint16 currencyId) external view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions); function getDepositParameters(uint16 currencyId) external view returns (int256[] memory depositShares, int256[] memory leverageThresholds); function nTokenAddress(uint16 currencyId) external view returns (address); function getNoteToken() external view returns (address); function getOwnershipStatus() external view returns (address owner, address pendingOwner); function getGlobalTransferOperatorStatus(address operator) external view returns (bool isAuthorized); function getAuthorizedCallbackContractStatus(address callback) external view returns (bool isAuthorized); function getSecondaryIncentiveRewarder(uint16 currencyId) external view returns (address incentiveRewarder); function getSettlementRate(uint16 currencyId, uint40 maturity) external view returns (AssetRateParameters memory); function getMarket( uint16 currencyId, uint256 maturity, uint256 settlementDate ) external view returns (MarketParameters memory); function getActiveMarkets(uint16 currencyId) external view returns (MarketParameters[] memory); function getActiveMarketsAtBlockTime(uint16 currencyId, uint32 blockTime) external view returns (MarketParameters[] memory); function getReserveBalance(uint16 currencyId) external view returns (int256 reserveBalance); function getNTokenPortfolio(address tokenAddress) external view returns (PortfolioAsset[] memory liquidityTokens, PortfolioAsset[] memory netfCashAssets); function getNTokenAccount(address tokenAddress) external view returns ( uint16 currencyId, uint256 totalSupply, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, bytes5 nTokenParameters, int256 cashBalance, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ); function getAccount(address account) external view returns ( AccountContext memory accountContext, AccountBalance[] memory accountBalances, PortfolioAsset[] memory portfolio ); function getAccountContext(address account) external view returns (AccountContext memory); function getAccountBalance(uint16 currencyId, address account) external view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime ); function getAccountPortfolio(address account) external view returns (PortfolioAsset[] memory); function getfCashNotional( address account, uint16 currencyId, uint256 maturity ) external view returns (int256); function getAssetsBitmap(address account, uint16 currencyId) external view returns (bytes32); function getFreeCollateral(address account) external view returns (int256, int256[] memory); function getTreasuryManager() external view returns (address); function getReserveBuffer(uint16 currencyId) external view returns (uint256); function getLendingPool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../internal/portfolio/PortfolioHandler.sol"; import "../internal/balances/BalanceHandler.sol"; import "../internal/settlement/SettlePortfolioAssets.sol"; import "../internal/settlement/SettleBitmapAssets.sol"; import "../internal/AccountContextHandler.sol"; /// @notice External library for settling assets library SettleAssetsExternal { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; event AccountSettled(address indexed account); /// @notice Settles an account, returns the new account context object after settlement. /// @dev The memory location of the account context object is not the same as the one returned. function settleAccount( address account, AccountContext memory accountContext ) external returns (AccountContext memory) { // Defensive check to ensure that this is a valid settlement require(accountContext.mustSettleAssets()); SettleAmount[] memory settleAmounts; PortfolioState memory portfolioState; if (accountContext.isBitmapEnabled()) { (int256 settledCash, uint256 blockTimeUTC0) = SettleBitmapAssets.settleBitmappedCashGroup( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, block.timestamp ); require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow accountContext.nextSettleTime = uint40(blockTimeUTC0); settleAmounts = new SettleAmount[](1); settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash); } else { portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp); accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts); emit AccountSettled(account); return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./balances/BalanceHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; library AccountContextHandler { using PortfolioHandler for PortfolioState; bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF; event AccountContextUpdate(address indexed account); /// @notice Returns the account context of a given account function getAccountContext(address account) internal view returns (AccountContext memory) { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); return store[account]; } /// @notice Sets the account context of a given account function setAccountContext(AccountContext memory accountContext, address account) internal { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); store[account] = accountContext; emit AccountContextUpdate(account); } function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) { return accountContext.bitmapCurrencyId != 0; } /// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows /// an account to hold more fCash than a normal portfolio, except only in a single currency. /// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if /// it has no assets or debt so that we ensure no assets are left stranded. /// @param accountContext refers to the account where the bitmap will be enabled /// @param currencyId the id of the currency to enable /// @param blockTime the current block time to set the next settle time function enableBitmapForAccount( AccountContext memory accountContext, uint16 currencyId, uint256 blockTime ) internal view { require(!isBitmapEnabled(accountContext), "Cannot change bitmap"); require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id"); // Account cannot have assets or debts require(accountContext.assetArrayLength == 0, "Cannot have assets"); require(accountContext.hasDebt == 0x00, "Cannot have debt"); // Ensure that the active currency is set to false in the array so that there is no double // counting during FreeCollateral setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES); accountContext.bitmapCurrencyId = currencyId; // Setting this is required to initialize the assets bitmap uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime); require(nextSettleTime < type(uint40).max); // dev: blockTime overflow accountContext.nextSettleTime = uint40(nextSettleTime); } /// @notice Returns true if the context needs to settle function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) { uint256 blockTime = block.timestamp; if (isBitmapEnabled(accountContext)) { // nextSettleTime will be set to utc0 after settlement so we // settle if this is strictly less than utc0 return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime); } else { // 0 value occurs on an uninitialized account // Assets mature exactly on the blockTime (not one second past) so in this // case we settle on the block timestamp return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime; } } /// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account /// context active currencies list. /// @dev NOTE: this may be more efficient as a binary search since we know that the array /// is sorted function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId) internal pure returns (bool) { require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id bytes18 currencies = accountContext.activeCurrencies; if (accountContext.bitmapCurrencyId == currencyId) return true; while (currencies != 0x00) { uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (cid == currencyId) { // Currency found, return if it is active in balances or not return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES; } currencies = currencies << 16; } return false; } /// @notice Iterates through the active currency list and removes, inserts or does nothing /// to ensure that the active currency list is an ordered byte array of uint16 currency ids /// that refer to the currencies that an account is active in. /// /// This is called to ensure that currencies are active when the account has a non zero cash balance, /// a non zero nToken balance or a portfolio asset. function setActiveCurrency( AccountContext memory accountContext, uint256 currencyId, bool isActive, bytes2 flags ) internal pure { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id // If the bitmapped currency is already set then return here. Turning off the bitmap currency // id requires other logical handling so we will do it elsewhere. if (isActive && accountContext.bitmapCurrencyId == currencyId) return; bytes18 prefix; bytes18 suffix = accountContext.activeCurrencies; uint256 shifts; /// There are six possible outcomes from this search: /// 1. The currency id is in the list /// - it must be set to active, do nothing /// - it must be set to inactive, shift suffix and concatenate /// 2. The current id is greater than the one in the search: /// - it must be set to active, append to prefix and then concatenate the suffix, /// ensure that we do not lose the last 2 bytes if set. /// - it must be set to inactive, it is not in the list, do nothing /// 3. Reached the end of the list: /// - it must be set to active, check that the last two bytes are not set and then /// append to the prefix /// - it must be set to inactive, do nothing while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS)); // if matches and isActive then return, already in list if (cid == currencyId && isActive) { // set flag and return accountContext.activeCurrencies = accountContext.activeCurrencies | (bytes18(flags) >> (shifts * 16)); return; } // if matches and not active then shift suffix to remove if (cid == currencyId && !isActive) { // turn off flag, if both flags are off then remove suffix = suffix & ~bytes18(flags); if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16; accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16)); return; } // if greater than and isActive then insert into prefix if (cid > currencyId && isActive) { prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); // check that the total length is not greater than 9, meaning that the last // two bytes of the active currencies array should be zero require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies // append the suffix accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16)); return; } // if past the point of the currency id and not active, not in list if (cid > currencyId && !isActive) return; prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16)); suffix = suffix << 16; shifts += 1; } // If reached this point and not active then return if (!isActive) return; // if end and isActive then insert into suffix, check max length require(shifts < 9); // dev: AC: too many currencies accountContext.activeCurrencies = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); } function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) { bytes18 result; // This is required to clear the suffix as we append below bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS; uint256 shifts; // This loop will append all currencies that are active in balances into the result. while (suffix != 0x00) { if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { // If any flags are active, then append. result = result | (bytes18(bytes2(suffix)) >> shifts); shifts += 16; } suffix = suffix << 16; } return result; } /// @notice Stores a portfolio array and updates the account context information, this method should /// be used whenever updating a portfolio array except in the case of nTokens function storeAssetsAndUpdateContext( AccountContext memory accountContext, address account, PortfolioState memory portfolioState, bool isLiquidation ) internal { // Each of these parameters is recalculated based on the entire array of assets in store assets, // regardless of whether or not they have been updated. (bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) = portfolioState.storeAssets(account); accountContext.nextSettleTime = nextSettleTime; require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets accountContext.assetArrayLength = assetArrayLength; // During liquidation it is possible for an array to go over the max amount of assets allowed due to // liquidity tokens being withdrawn into fCash. if (!isLiquidation) { require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed } // Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning // a negative fCash balance. if (hasDebt) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } else { // Turns off the ASSET_DEBT flag accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; } // Clear the active portfolio active flags and they will be recalculated in the next step accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) { // Portfolio currencies will not have flags, it is just an byte array of all the currencies found // in a portfolio. They are appended in a sorted order so we can compare to the previous currency // and only set it if they are different. uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); } lastCurrency = currencyId; portfolioCurrencies = portfolioCurrencies << 16; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetHandler.sol"; import "./ExchangeRate.sol"; import "../markets/CashGroup.sol"; import "../AccountContextHandler.sol"; import "../balances/BalanceHandler.sol"; import "../portfolio/PortfolioHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenCalculations.sol"; import "../../math/SafeInt256.sol"; library FreeCollateral { using SafeInt256 for int256; using Bitmap for bytes; using ExchangeRate for ETHRate; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; using nTokenHandler for nTokenPortfolio; /// @dev This is only used within the library to clean up the stack struct FreeCollateralFactors { int256 netETHValue; bool updateContext; uint256 portfolioIndex; CashGroupParameters cashGroup; MarketParameters market; PortfolioAsset[] portfolio; AssetRateParameters assetRate; nTokenPortfolio nToken; } /// @notice Checks if an asset is active in the portfolio function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) { return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO; } /// @notice Checks if currency balances are active in the account returns them if true /// @return cash balance, nTokenBalance function _getCurrencyBalances(address account, bytes2 currencyBytes) private view returns (int256, int256) { if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // prettier-ignore ( int256 cashBalance, int256 nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, currencyId); return (cashBalance, nTokenBalance); } return (0, 0); } /// @notice Calculates the nToken asset value with a haircut set by governance /// @return the value of the account's nTokens after haircut, the nToken parameters function _getNTokenHaircutAssetPV( CashGroupParameters memory cashGroup, nTokenPortfolio memory nToken, int256 tokenBalance, uint256 blockTime ) internal view returns (int256, bytes6) { nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId); nToken.cashGroup = cashGroup; int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // (tokenBalance * nTokenValue * haircut) / totalSupply int256 nTokenHaircutAssetPV = tokenBalance .mul(nTokenAssetPV) .mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE])) .div(Constants.PERCENTAGE_DECIMALS) .div(nToken.totalSupply); // nToken.parameters is returned for use in liquidation return (nTokenHaircutAssetPV, nToken.parameters); } /// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and /// markets. The reason these are grouped together is because they both require storage reads of the same /// values. function _getPortfolioAndNTokenAssetValue( FreeCollateralFactors memory factors, int256 nTokenBalance, uint256 blockTime ) private view returns ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { // If the next asset matches the currency id then we need to calculate the cash group value if ( factors.portfolioIndex < factors.portfolio.length && factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId ) { // netPortfolioValue is in asset cash (netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue( factors.portfolio, factors.cashGroup, factors.market, blockTime, factors.portfolioIndex ); } else { netPortfolioValue = 0; } if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; nTokenParameters = 0; } } /// @notice Returns balance values for the bitmapped currency function _getBitmapBalanceValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns ( int256 cashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { int256 nTokenBalance; // prettier-ignore ( cashBalance, nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId); if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; } } /// @notice Returns portfolio value for the bitmapped currency function _getBitmapPortfolioValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns (int256) { (int256 netPortfolioValueUnderlying, bool bitmapHasDebt) = BitmapAssetsHandler.getifCashNetPresentValue( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, blockTime, factors.cashGroup, true // risk adjusted ); // Turns off has debt flag if it has changed bool contextHasAssetDebt = accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT; if (bitmapHasDebt && !contextHasAssetDebt) { // Turn on has debt accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; factors.updateContext = true; } else if (!bitmapHasDebt && contextHasAssetDebt) { // Turn off has debt accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; factors.updateContext = true; } // Return asset cash value return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying); } function _updateNetETHValue( uint256 currencyId, int256 netLocalAssetValue, FreeCollateralFactors memory factors ) private view returns (ETHRate memory) { ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId); // Converts to underlying first, ETH exchange rates are in underlying factors.netETHValue = factors.netETHValue.add( ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue)) ); return ethRate; } /// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account /// context needs to be updated. function getFreeCollateralStateful( address account, AccountContext memory accountContext, uint256 blockTime ) internal returns (int256, bool) { FreeCollateralFactors memory factors; bool hasCashDebt; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); if (netCashBalance < 0) hasCashDebt = true; int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(account, currencyBytes); if (netLocalAssetValue < 0) hasCashDebt = true; if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); // prettier-ignore ( int256 netPortfolioAssetValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioAssetValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { // NOTE: we must set the proper assetRate when we updateNetETHValue factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValue, factors); currencies = currencies << 16; } // Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e. // they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of // sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing // an account to do an extra free collateral check to turn off this setting. if ( accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT && !hasCashDebt ) { accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT; factors.updateContext = true; } return (factors.netETHValue, factors.updateContext); } /// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips /// all the update context logic. function getFreeCollateralView( address account, AccountContext memory accountContext, uint256 blockTime ) internal view returns (int256, int256[] memory) { FreeCollateralFactors memory factors; uint256 netLocalIndex; int256[] memory netLocalAssetValues = new int256[](10); if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); netLocalAssetValues[netLocalIndex] = netCashBalance .add(nTokenHaircutAssetValue) .add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue( accountContext.bitmapCurrencyId, netLocalAssetValues[netLocalIndex], factors ); netLocalIndex++; } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); int256 nTokenBalance; (netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances( account, currencyBytes ); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupView(currencyId); // prettier-ignore ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex] .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { factors.assetRate = AssetRate.buildAssetRateView(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors); netLocalIndex++; currencies = currencies << 16; } return (factors.netETHValue, netLocalAssetValues); } /// @notice Calculates the net value of a currency within a portfolio, this is a bit /// convoluted to fit into the stack frame function _calculateLiquidationAssetValue( FreeCollateralFactors memory factors, LiquidationFactors memory liquidationFactors, bytes2 currencyBytes, bool setLiquidationFactors, uint256 blockTime ) private returns (int256) { uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(liquidationFactors.account, currencyBytes); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); (int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; // If collateralCurrencyId is set to zero then this is a local currency liquidation if (setLiquidationFactors) { liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenParameters = nTokenParameters; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; } } else { factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } return netLocalAssetValue; } /// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information. function getLiquidationFactors( address account, AccountContext memory accountContext, uint256 blockTime, uint256 localCurrencyId, uint256 collateralCurrencyId ) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) { FreeCollateralFactors memory factors; LiquidationFactors memory liquidationFactors; // This is only set to reduce the stack size liquidationFactors.account = account; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); (int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioBalance = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance); factors.assetRate = factors.cashGroup.assetRate; ETHRate memory ethRate = _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); // If the bitmap currency id can only ever be the local currency where debt is held. // During enable bitmap we check that the account has no assets in their portfolio and // no cash debts. if (accountContext.bitmapCurrencyId == localCurrencyId) { liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // This will be the case during local currency or local fCash liquidation if (collateralCurrencyId == 0) { // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers. liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; liquidationFactors.nTokenParameters = nTokenParameters; } } } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); // This next bit of code here is annoyingly structured to get around stack size issues bool setLiquidationFactors; { uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); // Explicitly ensures that bitmap currency cannot be double counted require(tempId != accountContext.bitmapCurrencyId); setLiquidationFactors = (tempId == localCurrencyId && collateralCurrencyId == 0) || tempId == collateralCurrencyId; } int256 netLocalAssetValue = _calculateLiquidationAssetValue( factors, liquidationFactors, currencyBytes, setLiquidationFactors, blockTime ); uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors); if (currencyId == collateralCurrencyId) { // Ensure that this is set even if the cash group is not loaded, it will not be // loaded if the account only has a cash balance and no nTokens or assets liquidationFactors.collateralCashGroup.assetRate = factors.assetRate; liquidationFactors.collateralAssetAvailable = netLocalAssetValue; liquidationFactors.collateralETHRate = ethRate; } else if (currencyId == localCurrencyId) { // This branch will not be entered if bitmap is enabled liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers and it will have been set in // _calculateLiquidationAssetValue above because the account must have fCash assets, // there is no need to set cash group in this branch. } currencies = currencies << 16; } liquidationFactors.netETHValue = factors.netETHValue; require(liquidationFactors.netETHValue < 0, "Sufficient collateral"); // Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash // netting which will make further calculations incorrect. if (accountContext.assetArrayLength > 0) { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } return (liquidationFactors, factors.portfolio); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TransferAssets.sol"; import "../valuation/AssetHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; /// @notice Handles the management of an array of assets including reading from storage, inserting /// updating, deleting and writing back to storage. library PortfolioHandler { using SafeInt256 for int256; using AssetHandler for PortfolioAsset; // Mirror of LibStorage.MAX_PORTFOLIO_ASSETS uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @notice Primarily used by the TransferAssets library function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets) internal pure { for (uint256 i = 0; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; addAsset( portfolioState, asset.currencyId, asset.maturity, asset.assetType, asset.notional ); } } function _mergeAssetIntoArray( PortfolioAsset[] memory assetArray, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) private pure returns (bool) { for (uint256 i = 0; i < assetArray.length; i++) { PortfolioAsset memory asset = assetArray[i]; if ( asset.assetType != assetType || asset.currencyId != currencyId || asset.maturity != maturity ) continue; // Either of these storage states mean that some error in logic has occurred, we cannot // store this portfolio require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: portfolio handler deleted storage int256 newNotional = asset.notional.add(notional); // Liquidity tokens cannot be reduced below zero. if (AssetHandler.isLiquidityToken(assetType)) { require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance } require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow asset.notional = newNotional; asset.storageState = AssetStorageState.Update; return true; } return false; } /// @notice Adds an asset to a portfolio state in memory (does not write to storage) /// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity /// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional. function addAsset( PortfolioState memory portfolioState, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) internal pure { if ( // Will return true if merged _mergeAssetIntoArray( portfolioState.storedAssets, currencyId, maturity, assetType, notional ) ) return; if (portfolioState.lastNewAssetIndex > 0) { bool merged = _mergeAssetIntoArray( portfolioState.newAssets, currencyId, maturity, assetType, notional ); if (merged) return; } // At this point if we have not merged the asset then append to the array // Cannot remove liquidity that the portfolio does not have if (AssetHandler.isLiquidityToken(assetType)) { require(notional >= 0); // dev: portfolio handler negative liquidity token balance } require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow // Need to provision a new array at this point if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) { portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets); } // Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will // check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct. PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex]; newAsset.currencyId = currencyId; newAsset.maturity = maturity; newAsset.assetType = assetType; newAsset.notional = notional; newAsset.storageState = AssetStorageState.NoChange; portfolioState.lastNewAssetIndex += 1; } /// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do /// it too much function _extendNewAssetArray(PortfolioAsset[] memory newAssets) private pure returns (PortfolioAsset[] memory) { // Double the size of the new asset array every time we have to extend to reduce the number of times // that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there). uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2; PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength); for (uint256 i = 0; i < newAssets.length; i++) { extendedArray[i] = newAssets[i]; } return extendedArray; } /// @notice Takes a portfolio state and writes it to storage. /// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via /// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library. /// @return updated variables to update the account context with /// hasDebt: whether or not the portfolio has negative fCash assets /// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio /// uint8: the length of the storage array /// uint40: the new nextSettleTime for the portfolio function storeAssets(PortfolioState memory portfolioState, address account) internal returns ( bool, bytes32, uint8, uint40 ) { bool hasDebt; // NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is // set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate // 7 additional fCash assets for a total of 14 assets. Although even in this case all assets // would be of the same currency so it would not change the end result of the active currency // calculation. bytes32 portfolioActiveCurrencies; uint256 nextSettleTime; for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler // during valuation. require(asset.storageState != AssetStorageState.RevertIfStored); // Mark any zero notional assets as deleted if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) { deleteAsset(portfolioState, i); } } // First delete assets from asset storage to maintain asset storage indexes for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; if (asset.storageState == AssetStorageState.Delete) { // Delete asset from storage uint256 currentSlot = asset.storageSlot; assembly { sstore(currentSlot, 0x00) } } else { if (asset.storageState == AssetStorageState.Update) { PortfolioAssetStorage storage assetStorage; uint256 currentSlot = asset.storageSlot; assembly { assetStorage.slot := currentSlot } _storeAsset(asset, assetStorage); } // Update portfolio context for every asset that is in storage, whether it is // updated in storage or not. (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); } } // Add new assets uint256 assetStorageLength = portfolioState.storedAssetLength; mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; for (uint256 i = 0; i < portfolioState.newAssets.length; i++) { PortfolioAsset memory asset = portfolioState.newAssets[i]; if (asset.notional == 0) continue; require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: store assets deleted storage (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); _storeAsset(asset, storageArray[assetStorageLength]); assetStorageLength += 1; } // 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with // 2 bytes per currency require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow return ( hasDebt, portfolioActiveCurrencies, uint8(assetStorageLength), uint40(nextSettleTime) ); } /// @notice Updates context information during the store assets method function _updatePortfolioContext( PortfolioAsset memory asset, bool hasDebt, bytes32 portfolioActiveCurrencies, uint256 nextSettleTime ) private pure returns ( bool, bytes32, uint256 ) { uint256 settlementDate = asset.getSettlementDate(); // Tis will set it to the minimum settlement date if (nextSettleTime == 0 || nextSettleTime > settlementDate) { nextSettleTime = settlementDate; } hasDebt = hasDebt || asset.notional < 0; require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240); return (hasDebt, portfolioActiveCurrencies, nextSettleTime); } /// @dev Encodes assets for storage function _storeAsset( PortfolioAsset memory asset, PortfolioAssetStorage storage assetStorage ) internal { require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow assetStorage.currencyId = uint16(asset.currencyId); assetStorage.maturity = uint40(asset.maturity); assetStorage.assetType = uint8(asset.assetType); assetStorage.notional = int88(asset.notional); } /// @notice Deletes an asset from a portfolio /// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement /// by adding the offsetting negative position function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure { require(index < portfolioState.storedAssets.length); // dev: stored assets bounds require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index]; require( assetToDelete.storageState != AssetStorageState.Delete && assetToDelete.storageState != AssetStorageState.RevertIfStored ); // dev: cannot delete asset portfolioState.storedAssetLength -= 1; uint256 maxActiveSlotIndex; uint256 maxActiveSlot; // The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the // array so we search for it here. for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory a = portfolioState.storedAssets[i]; if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) { maxActiveSlot = a.storageSlot; maxActiveSlotIndex = i; } } if (index == maxActiveSlotIndex) { // In this case we are deleting the asset with the max storage slot so no swap is necessary. assetToDelete.storageState = AssetStorageState.Delete; return; } // Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly // so that when we call store assets they will be updated appropriately PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex]; ( assetToSwap.storageSlot, assetToDelete.storageSlot ) = ( assetToDelete.storageSlot, assetToSwap.storageSlot ); assetToSwap.storageState = AssetStorageState.Update; assetToDelete.storageState = AssetStorageState.Delete; } /// @notice Returns a portfolio array, will be sorted function getSortedPortfolio(address account, uint8 assetArrayLength) internal view returns (PortfolioAsset[] memory) { PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength); // No sorting required for length of 1 if (assets.length <= 1) return assets; _sortInPlace(assets); return assets; } /// @notice Builds a portfolio array from storage. The new assets hint parameter will /// be used to provision a new array for the new assets. This will increase gas efficiency /// so that we don't have to make copies when we extend the array. function buildPortfolioState( address account, uint8 assetArrayLength, uint256 newAssetsHint ) internal view returns (PortfolioState memory) { PortfolioState memory state; if (assetArrayLength == 0) return state; state.storedAssets = getSortedPortfolio(account, assetArrayLength); state.storedAssetLength = assetArrayLength; state.newAssets = new PortfolioAsset[](newAssetsHint); return state; } function _sortInPlace(PortfolioAsset[] memory assets) private pure { uint256 length = assets.length; uint256[] memory ids = new uint256[](length); for (uint256 k; k < length; k++) { PortfolioAsset memory asset = assets[k]; // Prepopulate the ids to calculate just once ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType); } // Uses insertion sort uint256 i = 1; while (i < length) { uint256 j = i; while (j > 0 && ids[j - 1] > ids[j]) { // Swap j - 1 and j (ids[j - 1], ids[j]) = (ids[j], ids[j - 1]); (assets[j - 1], assets[j]) = (assets[j], assets[j - 1]); j--; } i++; } } function _loadAssetArray(address account, uint8 length) private view returns (PortfolioAsset[] memory) { // This will overflow the storage pointer require(length <= MAX_PORTFOLIO_ASSETS); mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; PortfolioAsset[] memory assets = new PortfolioAsset[](length); for (uint256 i = 0; i < length; i++) { PortfolioAssetStorage storage assetStorage = storageArray[i]; PortfolioAsset memory asset = assets[i]; uint256 slot; assembly { slot := assetStorage.slot } asset.currencyId = assetStorage.currencyId; asset.maturity = assetStorage.maturity; asset.assetType = assetStorage.assetType; asset.notional = assetStorage.notional; asset.storageSlot = slot; } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Incentives.sol"; import "./TokenHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/FloatingPoint56.sol"; library BalanceHandler { using SafeInt256 for int256; using TokenHandler for Token; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; /// @notice Emitted when a cash balance changes event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); /// @notice Emitted when nToken supply changes (not the same as transfers) event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Emitted when reserve balance is updated event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance); /// @notice Emitted when reserve balance is harvested event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount); /// @notice Deposits asset tokens into an account /// @dev Handles two special cases when depositing tokens into an account. /// - If a token has transfer fees then the amount specified does not equal the amount that the contract /// will receive. Complete the deposit here rather than in finalize so that the contract has the correct /// balance to work with. /// - Force a transfer before finalize to allow a different account to deposit into an account /// @return assetAmountInternal which is the converted asset amount accounting for transfer fees function depositAssetToken( BalanceState memory balanceState, address account, int256 assetAmountExternal, bool forceTransfer ) internal returns (int256 assetAmountInternal) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); // dev: deposit asset token amount negative Token memory token = TokenHandler.getAssetToken(balanceState.currencyId); if (token.tokenType == TokenType.aToken) { // Handles special accounting requirements for aTokens assetAmountExternal = AaveHandler.convertToScaledBalanceExternal( balanceState.currencyId, assetAmountExternal ); } // Force transfer is used to complete the transfer before going to finalize if (token.hasTransferFee || forceTransfer) { // If the token has a transfer fee the deposit amount may not equal the actual amount // that the contract will receive. We handle the deposit here and then update the netCashChange // accordingly which is denominated in internal precision. int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal); // Convert the external precision to internal, it's possible that we lose dust amounts here but // this is unavoidable because we do not know how transfer fees are calculated. assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal); // Transfer has been called balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal); return assetAmountInternal; } else { assetAmountInternal = token.convertToInternal(assetAmountExternal); // Otherwise add the asset amount here. It may be net off later and we want to only do // a single transfer during the finalize method. Use internal precision to ensure that internal accounting // and external account remain in sync. // Transfer will be deferred balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .add(assetAmountInternal); // Returns the converted assetAmountExternal to the internal amount return assetAmountInternal; } } /// @notice Handle deposits of the underlying token /// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up /// with any underlying tokens left as dust on the contract. function depositUnderlyingToken( BalanceState memory balanceState, address account, int256 underlyingAmountExternal ) internal returns (int256) { if (underlyingAmountExternal == 0) return 0; require(underlyingAmountExternal > 0); // dev: deposit underlying token negative Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // This is the exact amount of underlying tokens the account has in external precision. if (underlyingToken.tokenType == TokenType.Ether) { // Underflow checked above require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance"); } else { underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal); } Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); int256 assetTokensReceivedExternalPrecision = assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal)); // cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different // type of asset token is listed in the future. It's possible if those tokens have a different precision dust may // accrue but that is not relevant now. int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision); // Transfer / mint has taken effect balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal); return assetTokensReceivedInternal; } /// @notice Finalizes an account's balances, handling any transfer logic required /// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken /// as the nToken is limited in what types of balances it can hold. function finalize( BalanceState memory balanceState, address account, AccountContext memory accountContext, bool redeemToUnderlying ) internal returns (int256 transferAmountExternal) { bool mustUpdate; if (balanceState.netNTokenTransfer < 0) { require( balanceState.storedNTokenBalance .add(balanceState.netNTokenSupplyChange) .add(balanceState.netNTokenTransfer) >= 0, "Neg nToken" ); } if (balanceState.netAssetTransferInternalPrecision < 0) { require( balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= 0, "Neg Cash" ); } // Transfer amount is checked inside finalize transfers in case when converting to external we // round down to zero. This returns the actual net transfer in internal precision as well. ( transferAmountExternal, balanceState.netAssetTransferInternalPrecision ) = _finalizeTransfers(balanceState, account, redeemToUnderlying); // No changes to total cash after this point int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange ); } if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) { // Final nToken balance is used to calculate the account incentive debt int256 finalNTokenBalance = balanceState.storedNTokenBalance .add(balanceState.netNTokenTransfer) .add(balanceState.netNTokenSupplyChange); // The toUint() call here will ensure that nToken balances never become negative Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint()); balanceState.storedNTokenBalance = finalNTokenBalance; if (balanceState.netNTokenSupplyChange != 0) { emit nTokenSupplyChange( account, uint16(balanceState.currencyId), balanceState.netNTokenSupplyChange ); } mustUpdate = true; } if (mustUpdate) { _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } accountContext.setActiveCurrency( balanceState.currencyId, // Set active currency to true if either balance is non-zero balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (balanceState.storedCashBalance < 0) { // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances // are examined accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } } /// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying /// is specified. function _finalizeTransfers( BalanceState memory balanceState, address account, bool redeemToUnderlying ) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) { Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Dust accrual to the protocol is possible if the token decimals is less than internal token precision. // See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal int256 assetTransferAmountExternal = assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision); if (assetTransferAmountExternal == 0) { return (0, 0); } else if (redeemToUnderlying && assetTransferAmountExternal < 0) { // We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than // zero then we will do a normal transfer instead. // We use the internal amount here and then scale it to the external amount so that there is // no loss of precision between our internal accounting and the external account. In this case // there will be no dust accrual in underlying tokens since we will transfer the exact amount // of underlying that was received. actualTransferAmountExternal = assetToken.redeem( balanceState.currencyId, account, // No overflow, checked above uint256(assetTransferAmountExternal.neg()) ); // In this case we're transferring underlying tokens, we want to convert the internal // asset transfer amount to store in cash balances assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal); } else { // NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it // will be converted to balanceOf denomination inside transfer actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal); // Convert the actual transferred amount assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal); } } /// @notice Special method for settling negative current cash debts. This occurs when an account /// has a negative fCash balance settle to cash. A settler may come and force the account to borrow /// at the prevailing 3 month rate /// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary. function setBalanceStorageForSettleCashDebt( address account, CashGroupParameters memory cashGroup, int256 amountToSettleAsset, AccountContext memory accountContext ) internal returns (int256) { require(amountToSettleAsset >= 0); // dev: amount to settle negative (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, cashGroup.currencyId); // Prevents settlement of positive balances require(cashBalance < 0, "Invalid settle balance"); if (amountToSettleAsset == 0) { // Symbolizes that the entire debt should be settled amountToSettleAsset = cashBalance.neg(); cashBalance = 0; } else { // A partial settlement of the debt require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle"); cashBalance = cashBalance.add(amountToSettleAsset); } // NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances // also have cash debts if (cashBalance == 0 && nTokenBalance == 0) { accountContext.setActiveCurrency( cashGroup.currencyId, false, Constants.ACTIVE_IN_BALANCES ); } _setBalanceStorage( account, cashGroup.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); // Emit the event here, we do not call finalize emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset); return amountToSettleAsset; } /** * @notice A special balance storage method for fCash liquidation to reduce the bytecode size. */ function setBalanceStorageForfCashLiquidation( address account, AccountContext memory accountContext, uint16 currencyId, int256 netCashChange ) internal { (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, currencyId); int256 newCashBalance = cashBalance.add(netCashChange); // If a cash balance is negative already we cannot put an account further into debt. In this case // the netCashChange must be positive so that it is coming out of debt. if (newCashBalance < 0) { require(netCashChange > 0, "Neg Cash"); // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check // where all balances are examined. In this case the has cash debt flag should // already be set (cash balances cannot get more negative) but we do it again // here just to be safe. accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } bool isActive = newCashBalance != 0 || nTokenBalance != 0; accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES); // Emit the event here, we do not call finalize emit CashBalanceChange(account, currencyId, netCashChange); _setBalanceStorage( account, currencyId, newCashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } /// @notice Helper method for settling the output of the SettleAssets method function finalizeSettleAmounts( address account, AccountContext memory accountContext, SettleAmount[] memory settleAmounts ) internal { for (uint256 i = 0; i < settleAmounts.length; i++) { SettleAmount memory amt = settleAmounts[i]; if (amt.netCashChange == 0) continue; ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) = getBalanceStorage(account, amt.currencyId); cashBalance = cashBalance.add(amt.netCashChange); accountContext.setActiveCurrency( amt.currencyId, cashBalance != 0 || nTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (cashBalance < 0) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } emit CashBalanceChange( account, uint16(amt.currencyId), amt.netCashChange ); _setBalanceStorage( account, amt.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } } /// @notice Special method for setting balance storage for nToken function setBalanceStorageForNToken( address nTokenAddress, uint256 currencyId, int256 cashBalance ) internal { require(cashBalance >= 0); // dev: invalid nToken cash balance _setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0); } /// @notice increments fees to the reserve function incrementFeeToReserve(uint256 currencyId, int256 fee) internal { require(fee >= 0); // dev: invalid fee // prettier-ignore (int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId); totalReserve = totalReserve.add(fee); _setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0); emit ReserveFeeAccrued(uint16(currencyId), fee); } /// @notice harvests excess reserve balance function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal { // parameters are validated by the caller reserve = reserve.subNoNeg(assetInternalRedeemAmount); _setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0); emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount); } /// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal { require(newBalance >= 0); // dev: invalid balance _setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0); emit ReserveBalanceUpdated(currencyId, newBalance); } /// @notice Sets internal balance storage. function _setBalanceStorage( address account, uint256 currencyId, int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) private { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow // Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow if (lastClaimTime == 0) { // In this case the account has migrated and we set the accountIncentiveDebt // The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never // encounter an overflow for accountIncentiveDebt require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt); } else { // In this case the last claim time has not changed and we do not update the last integral supply // (stored in the accountIncentiveDebt position) require(lastClaimTime == balanceStorage.lastClaimTime); } balanceStorage.lastClaimTime = uint32(lastClaimTime); balanceStorage.nTokenBalance = uint80(nTokenBalance); balanceStorage.cashBalance = int88(cashBalance); } /// @notice Gets internal balance storage, nTokens are stored alongside cash balances function getBalanceStorage(address account, uint256 currencyId) internal view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; nTokenBalance = balanceStorage.nTokenBalance; lastClaimTime = balanceStorage.lastClaimTime; if (lastClaimTime > 0) { // NOTE: this is only necessary to support the deprecated integral supply values, which are stored // in the accountIncentiveDebt slot accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt); } else { accountIncentiveDebt = balanceStorage.accountIncentiveDebt; } cashBalance = balanceStorage.cashBalance; } /// @notice Loads a balance state memory object /// @dev Balance state objects occupy a lot of memory slots, so this method allows /// us to reuse them if possible function loadBalanceState( BalanceState memory balanceState, address account, uint16 currencyId, AccountContext memory accountContext ) internal view { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id balanceState.currencyId = currencyId; if (accountContext.isActiveInBalances(currencyId)) { ( balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ) = getBalanceStorage(account, currencyId); } else { balanceState.storedCashBalance = 0; balanceState.storedNTokenBalance = 0; balanceState.lastClaimTime = 0; balanceState.accountIncentiveDebt = 0; } balanceState.netCashChange = 0; balanceState.netAssetTransferInternalPrecision = 0; balanceState.netNTokenTransfer = 0; balanceState.netNTokenSupplyChange = 0; } /// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state /// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts /// are migrated to the new incentive calculation function claimIncentivesManual(BalanceState memory balanceState, address account) internal returns (uint256 incentivesClaimed) { incentivesClaimed = Incentives.claimIncentives( balanceState, account, balanceState.storedNTokenBalance.toUint() ); _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../valuation/AssetHandler.sol"; import "../markets/Market.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; library SettlePortfolioAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; using PortfolioHandler for PortfolioState; using AssetHandler for PortfolioAsset; /// @dev Returns a SettleAmount array for the assets that will be settled function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime) private pure returns (SettleAmount[] memory) { uint256 currenciesSettled; uint256 lastCurrencyId = 0; if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0); // Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio // NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause // a revert, must wrap in an unchecked. for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // Assets settle on exactly blockTime if (asset.getSettlementDate() > blockTime) continue; // Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this // will work for the first asset if (lastCurrencyId != asset.currencyId) { lastCurrencyId = asset.currencyId; currenciesSettled++; } } // Actual currency ids will be set as we loop through the portfolio and settle assets SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled); if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId; return settleAmounts; } /// @notice Settles a portfolio array function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime) internal returns (SettleAmount[] memory) { AssetRateParameters memory settlementRate; SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime); MarketParameters memory market; if (settleAmounts.length == 0) return settleAmounts; uint256 settleAmountIndex; for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; uint256 settleDate = asset.getSettlementDate(); // Settlement date is on block time exactly if (settleDate > blockTime) continue; // On the first loop the lastCurrencyId is already set. if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) { // New currency in the portfolio settleAmountIndex += 1; settleAmounts[settleAmountIndex].currencyId = asset.currencyId; } int256 assetCash; if (asset.assetType == Constants.FCASH_ASSET_TYPE) { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); assetCash = settlementRate.convertFromUnderlying(asset.notional); portfolioState.deleteAsset(i); } else if (AssetHandler.isLiquidityToken(asset.assetType)) { Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate); int256 fCash; (assetCash, fCash) = market.removeLiquidity(asset.notional); // Assets mature exactly on block time if (asset.maturity > blockTime) { // If fCash has not yet matured then add it to the portfolio _settleLiquidityTokenTofCash(portfolioState, i, fCash); } else { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); // If asset has matured then settle fCash to asset cash assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash)); portfolioState.deleteAsset(i); } } settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex] .netCashChange .add(assetCash); } return settleAmounts; } /// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future function _settleLiquidityTokenTofCash( PortfolioState memory portfolioState, uint256 index, int256 fCash ) private pure { PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index]; // If the liquidity token's maturity is still in the future then we change the entry to be // an idiosyncratic fCash entry with the net fCash amount. if (index != 0) { // Check to see if the previous index is the matching fCash asset, this will be the case when the // portfolio is sorted PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1]; if ( fCashAsset.currencyId == liquidityToken.currencyId && fCashAsset.maturity == liquidityToken.maturity && fCashAsset.assetType == Constants.FCASH_ASSET_TYPE ) { // This fCash asset has not matured if we are settling to fCash fCashAsset.notional = fCashAsset.notional.add(fCash); fCashAsset.storageState = AssetStorageState.Update; portfolioState.deleteAsset(index); } } // We are going to delete this asset anyway, convert to an fCash position liquidityToken.assetType = Constants.FCASH_ASSET_TYPE; liquidityToken.notional = fCash; liquidityToken.storageState = AssetStorageState.Update; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../markets/AssetRate.sol"; import "../../global/LibStorage.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; /** * Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash * at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues * to correctly reference all actual maturities. fCash asset notional values are stored in *absolute* * time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime. * Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on * newSettleTime and the absolute times (maturities) that the previous bitmap references. */ library SettleBitmapAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Bitmap for bytes32; /// @notice Given a bitmap for a cash group and timestamps, will settle all assets /// that have matured and remap the bitmap to correspond to the current time. function settleBitmappedCashGroup( address account, uint256 currencyId, uint256 oldSettleTime, uint256 blockTime ) internal returns (int256 totalAssetCash, uint256 newSettleTime) { bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId); // This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and // `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason // that lastSettleBit is inclusive is that it refers to newSettleTime which always less // than the current block time. newSettleTime = DateTime.getTimeUTC0(blockTime); // If newSettleTime == oldSettleTime lastSettleBit will be zero require(newSettleTime >= oldSettleTime); // dev: new settle time before previous // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until // the closest maturity that is less than newSettleTime. (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime); if (lastSettleBit == 0) return (totalAssetCash, newSettleTime); // Returns the next bit that is set in the bitmap uint256 nextBitNum = bitmap.getNextBitNum(); while (nextBitNum != 0 && nextBitNum <= lastSettleBit) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); totalAssetCash = totalAssetCash.add( _settlefCashAsset(account, currencyId, maturity, blockTime) ); // Turn the bit off now that it is settled bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } bytes32 newBitmap; while (nextBitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); (uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity); require(isValid); // dev: invalid new bit num newBitmap = newBitmap.setBit(newBitNum, true); // Turn the bit off now that it is remapped bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap); } /// @dev Stateful settlement function to settle a bitmapped asset. Deletes the /// asset from storage after calculating it. function _settlefCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 blockTime ) private returns (int256 assetCash) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); int256 notional = store[account][currencyId][maturity].notional; // Gets the current settlement rate or will store a new settlement rate if it does not // yet exist. AssetRateParameters memory rate = AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime); assetCash = rate.convertFromUnderlying(notional); delete store[account][currencyId][maturity]; return assetCash; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./PortfolioHandler.sol"; import "./BitmapAssetsHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../math/SafeInt256.sol"; /// @notice Helper library for transferring assets from one portfolio to another library TransferAssets { using AccountContextHandler for AccountContext; using PortfolioHandler for PortfolioState; using SafeInt256 for int256; /// @notice Decodes asset ids function decodeAssetId(uint256 id) internal pure returns ( uint256 currencyId, uint256 maturity, uint256 assetType ) { assetType = uint8(id); maturity = uint40(id >> 8); currencyId = uint16(id >> 48); } /// @notice Encodes asset ids function encodeAssetId( uint256 currencyId, uint256 maturity, uint256 assetType ) internal pure returns (uint256) { require(currencyId <= Constants.MAX_CURRENCIES); require(maturity <= type(uint40).max); require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); return uint256( (bytes32(uint256(uint16(currencyId))) << 48) | (bytes32(uint256(uint40(maturity))) << 8) | bytes32(uint256(uint8(assetType))) ); } /// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure { for (uint256 i; i < assets.length; i++) { assets[i].notional = assets[i].notional.neg(); } } /// @dev Useful method for hiding the logic of updating an account. WARNING: the account /// context returned from this method may not be the same memory location as the account /// context provided if the account is settled. function placeAssetsInAccount( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal returns (AccountContext memory) { // If an account has assets that require settlement then placing assets inside it // may cause issues. require(!accountContext.mustSettleAssets(), "Account must settle"); if (accountContext.isBitmapEnabled()) { // Adds fCash assets into the account and finalized storage BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets); } else { PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, assets.length ); // This will add assets in memory portfolioState.addMultipleAssets(assets); // This will store assets and update the account context in memory accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../markets/DateTime.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AssetHandler { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; function isLiquidityToken(uint256 assetType) internal pure returns (bool) { return assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX; } /// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method /// calculates the settlement date for any PortfolioAsset. function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) { require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type // 3 month tokens and fCash tokens settle at maturity if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1); // Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is: // maturity = tRef + marketLength // Here we calculate: // tRef = (maturity - marketLength) + 90 days return asset.maturity.sub(marketLength).add(Constants.QUARTER); } /// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity. /// The formula is: e^(-rate * timeToMaturity). function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)); expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue)); expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64); int256 discountFactor = ABDKMath64x64.toInt(expValue); return discountFactor; } /// @notice Present value of an fCash asset without any risk adjustments. function getPresentfCashValue( int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate); require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more /// heavily than the oracle rate given and vice versa for negative fCash. function getRiskAdjustedPresentfCashValue( CashGroupParameters memory cashGroup, int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor; if (notional > 0) { // If fCash is positive then discounting by a higher rate will result in a smaller // discount factor (e ^ -x), meaning a lower positive fCash value. discountFactor = getDiscountFactor( timeToMaturity, oracleRate.add(cashGroup.getfCashHaircut()) ); } else { uint256 debtBuffer = cashGroup.getDebtBuffer(); // If the adjustment exceeds the oracle rate we floor the value of the fCash // at the notional value. We don't want to require the account to hold more than // absolutely required. if (debtBuffer >= oracleRate) return notional; discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer); } require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Returns the non haircut claims on cash and fCash by the liquidity token. function getCashClaims(PortfolioAsset memory token, MarketParameters memory market) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity); fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity); } /// @notice Returns the haircut claims on cash and fCash function getHaircutCashClaims( PortfolioAsset memory token, MarketParameters memory market, CashGroupParameters memory cashGroup ) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch // This won't overflow, the liquidity token haircut is stored as an uint8 int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType)); assetCash = _calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity); fCash = _calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity); return (assetCash, fCash); } /// @dev This is here to clean up the stack in getHaircutCashClaims function _calcToken( int256 numerator, int256 tokens, int256 haircut, int256 liquidity ) private pure returns (int256) { return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity); } /// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists) function getLiquidityTokenValue( uint256 index, CashGroupParameters memory cashGroup, MarketParameters memory market, PortfolioAsset[] memory assets, uint256 blockTime, bool riskAdjusted ) internal view returns (int256, int256) { PortfolioAsset memory liquidityToken = assets[index]; { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex( cashGroup.maxMarketIndex, liquidityToken.maturity, blockTime ); // Liquidity tokens can never be idiosyncratic require(!idiosyncratic); // dev: idiosyncratic liquidity token // This market will always be initialized, if a liquidity token exists that means the // market has some liquidity in it. cashGroup.loadMarket(market, marketIndex, true, blockTime); } int256 assetCashClaim; int256 fCashClaim; if (riskAdjusted) { (assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup); } else { (assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market); } // Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and // in that case we know the previous asset will be the matching fCash asset if (index > 0) { PortfolioAsset memory maybefCash = assets[index - 1]; if ( maybefCash.assetType == Constants.FCASH_ASSET_TYPE && maybefCash.currencyId == liquidityToken.currencyId && maybefCash.maturity == liquidityToken.maturity ) { // Net off the fCashClaim here and we will discount it to present value in the second pass. // WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio! maybefCash.notional = maybefCash.notional.add(fCashClaim); // This state will prevent the fCash asset from being stored. maybefCash.storageState = AssetStorageState.RevertIfStored; return (assetCashClaim, 0); } } // If not matching fCash asset found then get the pv directly if (riskAdjusted) { int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate ); return (assetCashClaim, pv); } else { int256 pv = getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate); return (assetCashClaim, pv); } } /// @notice Returns present value of all assets in the cash group as asset cash and the updated /// portfolio index where the function has ended. /// @return the value of the cash group in asset cash function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex ) internal view returns (int256, uint256) { int256 presentValueAsset; int256 presentValueUnderlying; // First calculate value of liquidity tokens because we need to net off fCash value // before discounting to present value for (uint256 i = portfolioIndex; i < assets.length; i++) { if (!isLiquidityToken(assets[i].assetType)) continue; if (assets[i].currencyId != cashGroup.currencyId) break; (int256 assetCashClaim, int256 pv) = getLiquidityTokenValue( i, cashGroup, market, assets, blockTime, true // risk adjusted ); presentValueAsset = presentValueAsset.add(assetCashClaim); presentValueUnderlying = presentValueUnderlying.add(pv); } uint256 j = portfolioIndex; for (; j < assets.length; j++) { PortfolioAsset memory a = assets[j]; if (a.assetType != Constants.FCASH_ASSET_TYPE) continue; // If we hit a different currency id then we've accounted for all assets in this currency // j will mark the index where we don't have this currency anymore if (a.currencyId != cashGroup.currencyId) break; uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime); int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, a.notional, a.maturity, blockTime, oracleRate ); presentValueUnderlying = presentValueUnderlying.add(pv); } presentValueAsset = presentValueAsset.add( cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying) ); return (presentValueAsset, j); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../AccountContextHandler.sol"; import "../markets/CashGroup.sol"; import "../valuation/AssetHandler.sol"; import "../../math/Bitmap.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library BitmapAssetsHandler { using SafeMath for uint256; using SafeInt256 for int256; using Bitmap for bytes32; using CashGroup for CashGroupParameters; using AccountContextHandler for AccountContext; function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) { mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); return store[account][currencyId]; } function setAssetsBitmap( address account, uint256 currencyId, bytes32 assetsBitmap ) internal { require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets"); mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); store[account][currencyId] = assetsBitmap; } function getifCashNotional( address account, uint256 currencyId, uint256 maturity ) internal view returns (int256 notional) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); return store[account][currencyId][maturity].notional; } /// @notice Adds multiple assets to a bitmap portfolio function addMultipleifCashAssets( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal { require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set uint256 currencyId = accountContext.bitmapCurrencyId; for (uint256 i; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets int256 finalNotional; finalNotional = addifCashAsset( account, currencyId, asset.maturity, accountContext.nextSettleTime, asset.notional ); if (finalNotional < 0) accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } } /// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory /// but not in storage. /// @return the updated assets bitmap and the final notional amount function addifCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 nextSettleTime, int256 notional ) internal returns (int256) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; (uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity); require(isExact); // dev: invalid maturity in set ifcash asset if (assetsBitmap.isBitSet(bitNum)) { // Bit is set so we read and update the notional amount int256 finalNotional = notional.add(fCashSlot.notional); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); // If the new notional is zero then turn off the bit if (finalNotional == 0) { assetsBitmap = assetsBitmap.setBit(bitNum, false); } setAssetsBitmap(account, currencyId, assetsBitmap); return finalNotional; } if (notional != 0) { // Bit is not set so we turn it on and update the mapping directly, no read required. require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(notional); assetsBitmap = assetsBitmap.setBit(bitNum, true); setAssetsBitmap(account, currencyId, assetsBitmap); } return notional; } /// @notice Returns the present value of an asset function getPresentValue( address account, uint256 currencyId, uint256 maturity, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256) { int256 notional = getifCashNotional(account, currencyId, maturity); // In this case the asset has matured and the total value is just the notional amount if (maturity <= blockTime) { return notional; } else { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); if (riskAdjusted) { return AssetHandler.getRiskAdjustedPresentfCashValue( cashGroup, notional, maturity, blockTime, oracleRate ); } else { return AssetHandler.getPresentfCashValue( notional, maturity, blockTime, oracleRate ); } } } function getNetPresentValueFromBitmap( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted, bytes32 assetsBitmap ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 pv = getPresentValue( account, currencyId, maturity, blockTime, cashGroup, riskAdjusted ); totalValueUnderlying = totalValueUnderlying.add(pv); if (pv < 0) hasDebt = true; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } } /// @notice Get the net present value of all the ifCash assets function getifCashNetPresentValue( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); return getNetPresentValueFromBitmap( account, currencyId, nextSettleTime, blockTime, cashGroup, riskAdjusted, assetsBitmap ); } /// @notice Returns the ifCash assets as an array function getifCashArray( address account, uint256 currencyId, uint256 nextSettleTime ) internal view returns (PortfolioAsset[] memory) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 notional = getifCashNotional(account, currencyId, maturity); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notional; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../interfaces/chainlink/AggregatorV2V3Interface.sol"; import "../../interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) /// - aToken: Aave interest bearing tokens enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // Accumulator for incentives that the account no longer has a claim over uint256 accountIncentiveDebt; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; // Reserved bytes for future usage bytes15 _unused; // Set to true if a secondary rewarder is set bool hasSecondaryRewarder; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // Incentives that the account no longer has a claim over uint56 accountIncentiveDebt; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. This is the deprecated version struct nTokenTotalSupplyStorage_deprecated { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // How many NOTE incentives should be issued per nToken in 1e18 precision uint128 accumulatedNOTEPerNToken; // Last timestamp when the accumulation happened uint32 lastAccumulatedTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 accountIncentiveDebt; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Each bit set in this mask marks where an active market should be in the bitmap // if the first bit refers to the reference time. Used to detect idiosyncratic // fcash in the nToken accounts bytes32 internal constant ACTIVE_MARKETS_MASK = ( MSB >> ( 90 - 1) | // 3 month MSB >> (105 - 1) | // 6 month MSB >> (135 - 1) | // 1 year MSB >> (147 - 1) | // 2 year MSB >> (183 - 1) | // 5 year MSB >> (211 - 1) | // 10 year MSB >> (251 - 1) // 20 year ); // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library DateTime { using SafeMath for uint256; /// @notice Returns the current reference time which is how all the AMM dates are calculated. function getReferenceTime(uint256 blockTime) internal pure returns (uint256) { require(blockTime >= Constants.QUARTER); return blockTime - (blockTime % Constants.QUARTER); } /// @notice Truncates a date to midnight UTC time function getTimeUTC0(uint256 time) internal pure returns (uint256) { require(time >= Constants.DAY); return time - (time % Constants.DAY); } /// @notice These are the predetermined market offsets for trading /// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group. function getTradedMarket(uint256 index) internal pure returns (uint256) { if (index == 1) return Constants.QUARTER; if (index == 2) return 2 * Constants.QUARTER; if (index == 3) return Constants.YEAR; if (index == 4) return 2 * Constants.YEAR; if (index == 5) return 5 * Constants.YEAR; if (index == 6) return 10 * Constants.YEAR; if (index == 7) return 20 * Constants.YEAR; revert("Invalid index"); } /// @notice Determines if the maturity falls on one of the valid on chain market dates. function isValidMarketMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); if (maturity % Constants.QUARTER != 0) return false; uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true; } return false; } /// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case. function isValidMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { uint256 tRef = DateTime.getReferenceTime(blockTime); uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex)); // Cannot trade past max maturity if (maturity > maxMaturity) return false; // prettier-ignore (/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity); return isValid; } /// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic /// will return the nearest market index that is larger than the maturity. /// @return uint marketIndex, bool isIdiosyncratic function getMarketIndex( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (uint256, bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i)); // If market matches then is not idiosyncratic if (marketMaturity == maturity) return (i, false); // Returns the market that is immediately greater than the maturity if (marketMaturity > maturity) return (i, true); } revert("CG: no market found"); } /// @notice Given a bit number and the reference time of the first bit, returns the bit number /// of a given maturity. /// @return bitNum and a true or false if the maturity falls on the exact bit function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool) { uint256 blockTimeUTC0 = getTimeUTC0(blockTime); // Maturities must always divide days evenly if (maturity % Constants.DAY != 0) return (0, false); // Maturity cannot be in the past if (blockTimeUTC0 >= maturity) return (0, false); // Overflow check done above // daysOffset has no remainders, checked above uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY; // These if statements need to fall through to the next one if (daysOffset <= Constants.MAX_DAY_OFFSET) { return (daysOffset, true); } else if (daysOffset <= Constants.MAX_WEEK_OFFSET) { // (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0 // (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion // This returns the offset from the previous max offset in days uint256 offsetInDays = daysOffset - Constants.MAX_DAY_OFFSET + (blockTimeUTC0 % Constants.WEEK) / Constants.DAY; return ( // This converts the offset in days to its corresponding bit position, truncating down // if it does not divide evenly into DAYS_IN_WEEK Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK, (offsetInDays % Constants.DAYS_IN_WEEK) == 0 ); } else if (daysOffset <= Constants.MAX_MONTH_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_WEEK_OFFSET + (blockTimeUTC0 % Constants.MONTH) / Constants.DAY; return ( Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH, (offsetInDays % Constants.DAYS_IN_MONTH) == 0 ); } else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_MONTH_OFFSET + (blockTimeUTC0 % Constants.QUARTER) / Constants.DAY; return ( Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER, (offsetInDays % Constants.DAYS_IN_QUARTER) == 0 ); } // This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20 // year max maturity return (256, false); } /// @notice Given a bit number and a block time returns the maturity that the bit number /// should reference. Bit numbers are one indexed. function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum) internal pure returns (uint256) { require(bitNum != 0); // dev: cash group get maturity from bit num is zero require(bitNum <= 256); // dev: cash group get maturity from bit num overflow uint256 blockTimeUTC0 = getTimeUTC0(blockTime); uint256 firstBit; if (bitNum <= Constants.WEEK_BIT_OFFSET) { return blockTimeUTC0 + bitNum * Constants.DAY; } else if (bitNum <= Constants.MONTH_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_DAY_OFFSET * Constants.DAY - // This backs up to the day that is divisible by a week (blockTimeUTC0 % Constants.WEEK); return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK; } else if (bitNum <= Constants.QUARTER_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_WEEK_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.MONTH); return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH; } else { firstBit = blockTimeUTC0 + Constants.MAX_MONTH_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.QUARTER); return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER; } } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetRate.sol"; import "./CashGroup.sol"; import "./DateTime.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; // Max positive value for a ABDK64x64 integer int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; /// @notice Add liquidity to a market, assuming that it is initialized. If not then /// this method will revert and the market must be initialized first. /// Return liquidityTokens and negative fCash to the portfolio function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); require(assetCash > 0); // dev: negative asset cash liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); // No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion. fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); // Flip the sign to represent the LP's net position fCash = fCash.neg(); } /// @notice Remove liquidity from a market, assuming that it is initialized. /// Return assetCash and positive fCash to the portfolio function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); require(tokensToRemove > 0); // dev: negative tokens to remove assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } /// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive /// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory. /// @param market the current market state /// @param cashGroup cash group configuration parameters /// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change /// to the market is in the opposite direction. /// @param timeToMaturity number of seconds until maturity /// @return netAssetCash, netAssetCashToReserve function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { // We return false if there is not enough fCash to support this trade. // if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail // if fCashToAccount < 0 and totalfCash > 0 then this will always pass if (market.totalfCash <= fCashToAccount) return (0, 0); // Calculates initial rate factors for the trade (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); // Calculates the exchange rate from cash to fCash before any liquidity fees // are applied int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } // Given the exchange rate, returns the net cash amounts to apply to each of the // three relevant balances. (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); // Signifies a failed net cash amount calculation if (netCashToAccount == 0) return (0, 0); { // Set the new implied interest rate after the trade has taken effect, this // will be used to calculate the next trader's interest rate. market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); // It's technically possible that the implied rate is actually exactly zero (or // more accurately the natural log rounds down to zero) but we will still fail // in this case. If this does happen we may assume that markets are not initialized. if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } /// @notice Returns factors for calculating exchange rates /// @return /// rateScalar: a scalar value in rate precision that defines the slope of the line /// totalCashUnderlying: the converted asset cash to underlying cash for calculating /// the exchange rates for the trade /// rateAnchor: an offset from the x axis to maintain interest rate continuity over time function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // This would result in a divide by zero if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); // Get the rate anchor given the market state, this will establish the baseline for where // the exchange rate is set. int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } /// @dev Returns net asset cash amounts to the account, the market and the reserve /// @return /// netCashToAccount: this is a positive or negative amount of cash change to the account /// netCashToMarket: this is a positive or negative amount of cash change in the market // netCashToReserve: this is always a positive amount of cash accrued to the reserve function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { // Fees are specified in basis points which is an rate precision denomination. We convert this to // an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply // or divide depending on the side of the trade). // tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity) // tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity) // cash = fCash / exchangeRate, exchangeRate > 1 int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { // Lending // Dividing reduces exchange rate, lending should receive less fCash for cash int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); // It's possible that the fee pushes exchange rates into negative territory. This is not possible // when borrowing. If this happens then the trade has failed. if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate // preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate) // postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate) // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1) // netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1) // netFee = preFeeCashToAccount * (1 - feeExchangeRate) // RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0 fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); } else { // Borrowing // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1) // netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate) // NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number // preFee * (1 - fee) / fee will be negative, use neg() to flip to positive // RATE_PRECISION - fee will be negative fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( // postFeeCashToAccount = preFeeCashToAccount - fee preFeeCashToAccount.sub(fee), // netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve) (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), cashToReserve ); } /// @notice Sets the new market state /// @return /// netAssetCashToAccount: the positive or negative change in asset cash to the account /// assetCashToReserve: the positive amount of cash that accrues to the reserve function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); // Set storage checks that total asset cash is above zero market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); // Sets the trade time for the next oracle update market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } /// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable /// across time or markets but implied rates are. The goal here is to ensure that the implied rate /// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied /// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage /// which will hurt the liquidity providers. /// /// The rate anchor will update as the market rolls down to maturity. The calculation is: /// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME) /// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar /// /// where: /// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity') /// (calculated when the last trade in the market was made) /// @return the new rate anchor and a boolean that signifies success function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { // This is the exchange rate at the new time to maturity int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { // totalfCash / (totalfCash + totalCashUnderlying) int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } /// @notice Calculates the current market implied rate. /// @return the implied rate and a bool that is true on success function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { // This will check for exchange rates < Constants.RATE_PRECISION (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; // Uses continuous compounding to calculate the implied rate: // ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity int128 rate = ABDKMath64x64.fromInt(exchangeRate); // Scales down to a floating point for LN int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); // We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION // inside getExchangeRate int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); // Scales up to a fixed point uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); // lnRate * IMPLIED_RATE_TIME / ttm uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); // Implied rates over 429% will overflow, this seems like a safe assumption if (impliedRate > type(uint32).max) return 0; return impliedRate; } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// formula is E = e^rt function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } /// @notice Returns the exchange rate between fCash and cash for the given market /// Calculates the following exchange rate: /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalfCash / (totalfCash + totalUnderlyingCash) /// @dev has an underscore to denote as private but is marked internal for the mock function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); // This is the proportion scaled by Constants.RATE_PRECISION // (totalfCash + fCash) / (totalfCash + totalCashUnderlying) int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); // This limit is here to prevent the market from reaching extremely high interest rates via an // excessively large proportion (high amounts of fCash relative to cash). // Market proportion can only increase via borrowing (fCash is added to the market and cash is // removed). Over time, the returns from asset cash will slightly decrease the proportion (the // value of cash underlying in the market must be monotonically increasing). Therefore it is not // possible for the proportion to go over max market proportion unless borrowing occurs. if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // lnProportion / rateScalar + rateAnchor int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); // Do not succeed if interest rates fall below 1 if (rate < Constants.RATE_PRECISION) { return (0, false); } else { return (rate, true); } } /// @dev This method calculates the log of the proportion inside the logit function which is /// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with /// fixed point precision and the ABDK library. function _logProportion(int256 proportion) internal pure returns (int256, bool) { // This will result in divide by zero, short circuit if (proportion == Constants.RATE_PRECISION) return (0, false); // Convert proportion to what is used inside the logit function (p / (1-p)) int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); // ABDK does not handle log of numbers that are less than 1, in order to get the right value // scaled by RATE_PRECISION we use the log identity: // (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION int128 abdkProportion = ABDKMath64x64.fromInt(logitP); // Here, abdk will revert due to negative log so abort if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } /// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value /// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example, /// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates. /// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then /// be liquidated. /// /// Oracle rates are calculated when the market is loaded from storage. /// /// The oracle rate is a lagged weighted average over a short term price window. If we are past /// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the /// weighted average: /// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow + /// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow) function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero // This can occur when using a view function get to a market state in the past if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { // If past the time window just return the lastImpliedRate return lastImpliedRate; } // (currentTs - previousTs) / timeWindow uint256 lastTradeWeight = timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); // 1 - (currentTs - previousTs) / timeWindow uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; // If the oracle rate is set to zero this can only be because the markets have past their settlement // date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated // during this time, but market initialization can be called by anyone so the actual time that this condition // exists for should be quite short. require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } /// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method /// which ensures that the rate oracle is set properly. function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { // Market object always uses the most current reference time as the settlement date mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; } else { market.totalLiquidity = 0; } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); // Oracle rate does not change on liquidity uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { // On initialization we have not yet calculated the storage slot so we get it here. mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately. function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this /// is mainly used in the InitializeMarketAction contract. function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } /// Uses Newton's method to converge on an fCash amount given the amount of /// cash. The relation between cash and fcash is: /// cashAmount * exchangeRate * fee + fCash = 0 /// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor /// p = (totalfCash - fCash) / (totalfCash + totalCash) /// if cashAmount < 0: fee = feeRate ^ -1 /// if cashAmount > 0: fee = feeRate /// /// Newton's method is: /// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash) /// /// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash /// /// (totalfCash + totalCash) /// exchangeRate'(fCash) = - ------------------------------------------ /// (totalfCash - fCash) * (totalCash + fCash) /// /// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29 /// /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) /// /// NOTE: each iteration costs about 11.3k so this is only done via a view function. function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); require(success); // dev: invalid exchange rate int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } /// @dev Calculates: f(fCash) / f'(fCash) /// f(fCash) = cashAmount * exchangeRate * fee + fCash /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; // rateScalar * (totalfCash - fCash) * (totalCash + fCash) // Precision: TOKEN_PRECISION ^ 2 int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { // Lending exchangeRate = exchangeRate.divInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount / fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); } else { // Borrowing exchangeRate = exchangeRate.mulInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount * fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } // 1 - numerator / denominator // Precision: TOKEN_PRECISION derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); // f(fCash) = cashAmount * exchangeRate * fee + fCash // NOTE: exchangeRate at this point already has the fee taken into account int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); numerator = numerator.add(fCashGuess); // f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION // here instead of RATE_PRECISION return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; interface IRewarder { function claimRewards( address account, uint16 currencyId, uint256 nTokenBalanceBefore, uint256 nTokenBalanceAfter, int256 netNTokenSupplyChange, uint256 NOTETokensClaimed ) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; struct LendingPoolStorage { ILendingPool lendingPool; } interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (ReserveData memory); // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TokenHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenSupply.sol"; import "../../math/SafeInt256.sol"; import "../../external/MigrateIncentives.sol"; import "../../../interfaces/notional/IRewarder.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Incentives { using SafeMath for uint256; using SafeInt256 for int256; /// @notice Calculates the total incentives to claim including those claimed under the previous /// less accurate calculation. Once an account is migrated it will only claim incentives under /// the more accurate regime function calculateIncentivesToClaim( BalanceState memory balanceState, address tokenAddress, uint256 accumulatedNOTEPerNToken, uint256 finalNTokenBalance ) internal view returns (uint256 incentivesToClaim) { if (balanceState.lastClaimTime > 0) { // If lastClaimTime is set then the account had incentives under the // previous regime. Will calculate the final amount of incentives to claim here // under the previous regime. incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation( tokenAddress, balanceState.storedNTokenBalance.toUint(), balanceState.lastClaimTime, // In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under // the old calculation balanceState.accountIncentiveDebt ); // This marks the account as migrated and lastClaimTime will no longer be used balanceState.lastClaimTime = 0; // This value will be set immediately after this, set this to zero so that the calculation // establishes a new baseline. balanceState.accountIncentiveDebt = 0; } // If an account was migrated then they have no accountIncentivesDebt and should accumulate // incentives based on their share since the new regime calculation started. // If an account is just initiating their nToken balance then storedNTokenBalance will be zero // and they will have no incentives to claim. // This calculation uses storedNTokenBalance which is the balance of the account up until this point, // this is important to ensure that the account does not claim for nTokens that they will mint or // redeem on a going forward basis. // The calculation below has the following precision: // storedNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION incentivesToClaim = incentivesToClaim.add( balanceState.storedNTokenBalance.toUint() .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION) .sub(balanceState.accountIncentiveDebt) ); // Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion // of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance // here instead of storedNTokenBalance to mark the overall incentives claim that the account // does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt // because accumulatedNOTEPerNToken is already an aggregated value. // The calculation below has the following precision: // finalNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION balanceState.accountIncentiveDebt = finalNTokenBalance .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION); } /// @notice Incentives must be claimed every time nToken balance changes. /// @dev BalanceState.accountIncentiveDebt is updated in place here function claimIncentives( BalanceState memory balanceState, address account, uint256 finalNTokenBalance ) internal returns (uint256 incentivesToClaim) { uint256 blockTime = block.timestamp; address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId); // This will updated the nToken storage and return what the accumulatedNOTEPerNToken // is up until this current block time in 1e18 precision uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply( tokenAddress, balanceState.netNTokenSupplyChange, blockTime ); incentivesToClaim = calculateIncentivesToClaim( balanceState, tokenAddress, accumulatedNOTEPerNToken, finalNTokenBalance ); // If a secondary incentive rewarder is set, then call it IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress); if (address(rewarder) != address(0)) { rewarder.claimRewards( account, balanceState.currencyId, // When this method is called from finalize, the storedNTokenBalance has not // been updated to finalNTokenBalance yet so this is the balance before the change. balanceState.storedNTokenBalance.toUint(), finalNTokenBalance, // When the rewarder is called, totalSupply has been updated already so may need to // adjust its calculation using the net supply change figure here. Supply change // may be zero when nTokens are transferred. balanceState.netNTokenSupplyChange, incentivesToClaim ); } if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./Bitmap.sol"; /** * Packs an uint value into a "floating point" storage slot. Used for storing * lastClaimIntegralSupply values in balance storage. For these values, we don't need * to maintain exact precision but we don't want to be limited by storage size overflows. * * A floating point value is defined by the 48 most significant bits and an 8 bit number * of bit shifts required to restore its precision. The unpacked value will always be less * than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1. */ library FloatingPoint56 { function packTo56Bits(uint256 value) internal pure returns (uint56) { uint256 bitShift; // If the value is over the uint48 max value then we will shift it down // given the index of the most significant bit. We store this bit shift // in the least significant byte of the 56 bit slot available. if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47); uint256 shiftedValue = value >> bitShift; return uint56((shiftedValue << 8) | bitShift); } function unpackFrom56Bits(uint256 value) internal pure returns (uint256) { // The least significant 8 bits will be the amount to bit shift uint256 bitShift = uint256(uint8(value)); return ((value >> 8) << bitShift); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "../internal/nToken/nTokenHandler.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @notice Deployed library for migration of incentives from the old (inaccurate) calculation * to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate * calculation is inside `Incentives.sol` and this library holds the legacy calculation. System * migration code can be found in `MigrateIncentivesFix.sol` */ library MigrateIncentives { using SafeMath for uint256; /// @notice Calculates the claimable incentives for a particular nToken and account in the /// previous regime. This should only ever be called ONCE for an account / currency combination /// to get the incentives accrued up until the migration date. function migrateAccountFromPreviousCalculation( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) external view returns (uint256) { ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) = _getMigratedIncentiveValues(tokenAddress); // This if statement should never be true but we return 0 just in case if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0; // No overflow here, checked above. All incentives are claimed up until finalMigrationTime // using the finalTotalIntegralSupply. Both these values are set on migration and will not // change. uint256 timeSinceMigration = finalMigrationTime - lastClaimTime; // (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR uint256 incentiveRate = timeSinceMigration .mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) // Migration emission rate is stored as is, denominated in whole tokens .mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) .div(Constants.YEAR); // Returns the average supply using the integral of the total supply. uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration); if (avgTotalSupply == 0) return 0; uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply); // incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8 incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION)); return incentivesToClaim; } function _getMigratedIncentiveValues( address tokenAddress ) private view returns ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) { mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress]; // The total supply value is overridden as emissionRatePerYear during the initialization finalEmissionRatePerYear = d_nTokenStorage.totalSupply; finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply; finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../../global/Types.sol"; import "../../../global/LibStorage.sol"; import "../../../math/SafeInt256.sol"; import "../TokenHandler.sol"; import "../../../../interfaces/aave/IAToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AaveHandler { using SafeMath for uint256; using SafeInt256 for int256; int256 internal constant RAY = 1e27; int256 internal constant halfRAY = RAY / 2; bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector; /** * @notice Mints an amount of aTokens corresponding to the the underlying. * @param underlyingToken address of the underlying token to pass to Aave * @param underlyingAmountExternal amount of underlying to deposit, in external precision */ function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal { // In AaveV3 this method is renamed to supply() but deposit() is still available for // backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755 // We use deposit here so that mainnet-fork tests against Aave v2 will pass. LibStorage.getLendingPool().lendingPool.deposit( underlyingToken.tokenAddress, underlyingAmountExternal, address(this), 0 ); } /** * @notice Redeems and sends an amount of aTokens to the specified account * @param underlyingToken address of the underlying token to pass to Aave * @param account account to receive the underlying * @param assetAmountExternal amount of aTokens in scaledBalanceOf terms */ function redeem( Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { underlyingAmountExternal = convertFromScaledBalanceExternal( underlyingToken.tokenAddress, SafeInt256.toInt(assetAmountExternal) ).toUint(); LibStorage.getLendingPool().lendingPool.withdraw( underlyingToken.tokenAddress, underlyingAmountExternal, account ); } /** * @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest) * and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional * claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will * receive future Aave interest. * @dev There is no loss of precision within this function since it does the exact same calculation as Aave. * @param currencyId is the currency id * @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must * be positive in this function, this method is only called when depositing aTokens directly * @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will * be in external precision. */ function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId); // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress); // Mimic the WadRay math performed by Aave (but do it in int256 instead) int256 halfIndex = index / 2; // Overflow will occur when: (a * RAY + halfIndex) > int256.max require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY); // if index is zero then this will revert return (assetAmountExternal * RAY + halfIndex) / index; } /** * @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision) * and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest * that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions. * @dev There is no loss of precision because this does exactly what Aave's calculation would do * @param underlyingToken token address of the underlying asset * @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from * Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or * withdrawn (negative). * @return netBalanceExternal the Aave balanceOf equivalent as a signed integer */ function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) { if (netScaledBalanceExternal == 0) return 0; // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken); // Use the absolute value here so that the halfRay rounding is applied correctly for negative values int256 abs = netScaledBalanceExternal.abs(); // Mimic the WadRay math performed by Aave (but do it in int256 instead) // Overflow will occur when: (abs * index + halfRay) > int256.max // Here the first term is computed at compile time so it just does a division. If index is zero then // solidity will revert. require(abs <= (type(int256).max - halfRAY) / index); int256 absScaled = (abs * index + halfRAY) / RAY; return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg(); } /// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is /// always positive even though we are converting to a signed int function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) { return SafeInt256.toInt( LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./GenericToken.sol"; import "../../../../interfaces/compound/CErc20Interface.sol"; import "../../../../interfaces/compound/CEtherInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../global/Types.sol"; library CompoundHandler { using SafeMath for uint256; // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; function mintCETH(Token memory token) internal { // Reverts on error CEtherInterface(token.tokenAddress).mint{value: msg.value}(); } function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) { uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint"); } function redeemCETH( Token memory assetToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = address(this).balance; uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = address(this).balance; underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.transferNativeTokenOut(account, underlyingAmountExternal); } function redeem( Token memory assetToken, Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../../../../interfaces/IEIP20NonStandard.sol"; library GenericToken { bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector; /** * @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows * for overriding the balanceOf selector to use scaledBalanceOf for aTokens */ function checkBalanceViaSelector( address token, address account, bytes4 balanceOfSelector ) internal returns (uint256 balance) { (bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account)); require(success); (balance) = abi.decode(returnData, (uint256)); } function transferNativeTokenOut( address account, uint256 amount ) internal { // This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying // ETH they will have to withdraw the cETH token and then redeem it manually. payable(account).transfer(amount); } function safeTransferOut( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transfer(account, amount); checkReturnCode(); } function safeTransferIn( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transferFrom(account, address(this), amount); checkReturnCode(); } function checkReturnCode() internal pure { bool success; uint256[1] memory result; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := 1 // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(result, 0, 32) success := mload(result) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "ERC20"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); function UNDERLYING_ASSET_ADDRESS() external view returns (address); function symbol() external view returns (string memory); } interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } interface IATokenFull is IScaledBalanceToken, IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; import "./CTokenInterface.sol"; interface CErc20Interface { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CEtherInterface { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface IEIP20NonStandard { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved */ function approve(address spender, uint256 amount) external; /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CTokenInterface { /*** User Interface ***/ function underlying() external view returns (address); function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/Types.sol"; import "../global/Constants.sol"; /// @notice Helper methods for bitmaps, they are big-endian and 1-indexed. library Bitmap { /// @notice Set a bit on or off in a bitmap, index is 1-indexed function setBit( bytes32 bitmap, uint256 index, bool setOn ) internal pure returns (bytes32) { require(index >= 1 && index <= 256); // dev: set bit index bounds if (setOn) { return bitmap | (Constants.MSB >> (index - 1)); } else { return bitmap & ~(Constants.MSB >> (index - 1)); } } /// @notice Check if a bit is set function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) { require(index >= 1 && index <= 256); // dev: set bit index bounds return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB; } /// @notice Count the total bits set function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) { uint256 x = uint256(bitmap); x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555); x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333); x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4); x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F); x = x + (x >> 16); x = x + (x >> 32); x = x + (x >> 64); return (x & 0xFF) + (x >> 128 & 0xFF); } // Does a binary search over x to get the position of the most significant bit function getMSB(uint256 x) internal pure returns (uint256 msb) { // If x == 0 then there is no MSB and this method will return zero. That would // be the same as the return value when x == 1 (MSB is zero indexed), so instead // we have this require here to ensure that the values don't get mixed up. require(x != 0); // dev: get msb zero value if (x >= 0x100000000000000000000000000000000) { x >>= 128; msb += 128; } if (x >= 0x10000000000000000) { x >>= 64; msb += 64; } if (x >= 0x100000000) { x >>= 32; msb += 32; } if (x >= 0x10000) { x >>= 16; msb += 16; } if (x >= 0x100) { x >>= 8; msb += 8; } if (x >= 0x10) { x >>= 4; msb += 4; } if (x >= 0x4) { x >>= 2; msb += 2; } if (x >= 0x2) msb += 1; // No need to shift xc anymore } /// @dev getMSB returns a zero indexed bit number where zero is the first bit counting /// from the right (little endian). Asset Bitmaps are counted from the left (big endian) /// and one indexed. function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) { // Short circuit the search if bitmap is all zeros if (bitmap == 0x00) return 0; return 255 - getMSB(uint256(bitmap)) + 1; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; library nTokenCalculations { using Bitmap for bytes32; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using CashGroup for CashGroupParameters; /// @notice Returns the nToken present value denominated in asset terms. function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256) { int256 totalAssetPV; int256 totalUnderlyingPV; { uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken); // If the first asset maturity has passed (the 3 month), this means that all the LTs must // be settled except the 6 month (which is now the 3 month). We don't settle LTs except in // initialize markets so we calculate the cash value of the portfolio here. if (nextSettleTime <= blockTime) { // NOTE: this condition should only be present for a very short amount of time, which is the window between // when the markets are no longer tradable at quarter end and when the new markets have been initialized. // We time travel back to one second before maturity to value the liquidity tokens. Although this value is // not strictly correct the different should be quite slight. We do this to ensure that free collateral checks // for withdraws and liquidations can still be processed. If this condition persists for a long period of time then // the entire protocol will have serious problems as markets will not be tradable. blockTime = nextSettleTime - 1; } } // This is the total value in liquid assets (int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime); // Then get the total value in any idiosyncratic fCash residuals (if they exist) bytes32 ifCashBits = getNTokenifCashBits( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); int256 ifCashResidualUnderlyingPV = 0; if (ifCashBits != 0) { // Non idiosyncratic residuals have already been accounted for (ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, false, // nToken present value calculation does not use risk adjusted values ifCashBits ); } // Return the total present value denominated in asset terms return totalAssetValueInMarkets .add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV)) .add(nToken.cashBalance); } /** * @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts * in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken * portfolio. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to * the account's share of the total supply * @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually * withdrawn from markets */ function _getProportionalLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem ) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; tokensToWithdraw = new int256[](numMarkets); netfCash = new int256[](numMarkets); for (uint256 i = 0; i < numMarkets; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply); } } /** * @notice Returns the number of liquidity tokens to withdraw from each market if the nToken * has idiosyncratic residuals during nToken redeem. In this case the redeemer will take * their cash from the rest of the fCash markets, redeeming around the nToken. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param blockTime block time * @param ifCashBits the bits in the bitmap that represent ifCash assets * @return tokensToWithdraw array of tokens to withdraw from each corresponding market * @return netfCash array of netfCash amounts to go back to the account */ function getLiquidityTokenWithdraw( nTokenPortfolio memory nToken, int256 nTokensToRedeem, uint256 blockTime, bytes32 ifCashBits ) internal view returns (int256[] memory, int256[] memory) { // If there are no ifCash bits set then this will just return the proportion of all liquidity tokens if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem); ( int256 totalAssetValueInMarkets, int256[] memory netfCash ) = getNTokenMarketValue(nToken, blockTime); int256[] memory tokensToWithdraw = new int256[](netfCash.length); // NOTE: this total portfolio asset value does not include any cash balance the nToken may hold. // The redeemer will always get a proportional share of this cash balance and therefore we don't // need to account for it here when we calculate the share of liquidity tokens to withdraw. We are // only concerned with the nToken's portfolio assets in this method. int256 totalPortfolioAssetValue; { // Returns the risk adjusted net present value for the idiosyncratic residuals (int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, true, // use risk adjusted here to assess a penalty for withdrawing around the residual ifCashBits ); // NOTE: we do not include cash balance here because the account will always take their share // of the cash balance regardless of the residuals totalPortfolioAssetValue = totalAssetValueInMarkets.add( nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV) ); } // Loops through each liquidity token and calculates how much the redeemer can withdraw to get // the requisite amount of present value after adjusting for the ifCash residual value that is // not accessible via redemption. for (uint256 i = 0; i < tokensToWithdraw.length; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; // Redeemer's baseline share of the liquidity tokens based on total supply: // redeemerShare = totalTokens * nTokensToRedeem / totalSupply // Scalar factor to account for residual value (need to inflate the tokens to withdraw // proportional to the value locked up in ifCash residuals): // scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets // Final math equals: // tokensToWithdraw = redeemerShare * scalarFactor // tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue) // / (totalAssetValueInMarkets * totalSupply) tokensToWithdraw[i] = totalTokens .mul(nTokensToRedeem) .mul(totalPortfolioAssetValue); tokensToWithdraw[i] = tokensToWithdraw[i] .div(totalAssetValueInMarkets) .div(nToken.totalSupply); // This is the share of net fcash that will be credited back to the account netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens); } return (tokensToWithdraw, netfCash); } /// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by /// the liquidity tokens held in each market and their corresponding fCash positions. The formula /// can be described as: /// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash)) /// where netfCash = fCashClaim + fCash /// and fCash refers the the fCash position at the corresponding maturity function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256 totalAssetValue, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; netfCash = new int256[](numMarkets); MarketParameters memory market; for (uint256 i = 0; i < numMarkets; i++) { // Load the corresponding market into memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i]; uint256 maturity = liquidityToken.maturity; // Get the fCash claims and fCash assets. We do not use haircut versions here because // nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied // at the end of the calculation to the entire PV instead). (int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market); // fCash is denominated in underlying netfCash[i] = fCashClaim.add( BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, maturity ) ); // This calculates for a single liquidity token: // assetCashClaim + convertToAssetCash(pv(netfCash)) int256 netAssetValueInMarket = assetCashClaim.add( nToken.cashGroup.assetRate.convertFromUnderlying( AssetHandler.getPresentfCashValue( netfCash[i], maturity, blockTime, // No need to call cash group for oracle rate, it is up to date here // and we are assured to be referring to this market. market.oracleRate ) ) ); // Calculate the running total totalAssetValue = totalAssetValue.add(netAssetValueInMarket); } } /// @notice Returns just the bits in a bitmap that are idiosyncratic function getNTokenifCashBits( address tokenAddress, uint256 currencyId, uint256 lastInitializedTime, uint256 blockTime, uint256 maxMarketIndex ) internal view returns (bytes32) { // If max market index is less than or equal to 2, there are never ifCash assets by construction if (maxMarketIndex <= 2) return bytes32(0); bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId); // Handles the case when there are no assets at the first initialization if (assetsBitmap == 0) return assetsBitmap; uint256 tRef = DateTime.getReferenceTime(blockTime); if (tRef == lastInitializedTime) { // This is a more efficient way to turn off ifCash assets in the common case when the market is // initialized immediately return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK); } else { // In this branch, initialize markets has occurred past the time above. It would occur in these // two scenarios (both should be exceedingly rare): // 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef) // 2. somehow initialize markets has been delayed for more than 24 hours for (uint i = 1; i <= maxMarketIndex; i++) { // In this loop we get the maturity of each active market and turn off the corresponding bit // one by one. It is less efficient than the option above. uint256 maturity = tRef + DateTime.getTradedMarket(i); (uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity); assetsBitmap = assetsBitmap.setBit(bitNum, false); } return assetsBitmap; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; /** * @notice Storage layout for the system. Do not change this file once deployed, future storage * layouts must inherit this and increment the version number. */ contract StorageLayoutV1 { // The current maximum currency id uint16 internal maxCurrencyId; // Sets the state of liquidations being enabled during a paused state. Each of the four lower // bits can be turned on to represent one of the liquidation types being enabled. bytes1 internal liquidationEnabledState; // Set to true once the system has been initialized bool internal hasInitialized; /* Authentication Mappings */ // This is set to the timelock contract to execute governance functions address public owner; // This is set to an address of a router that can only call governance actions address public pauseRouter; // This is set to an address of a router that can only call governance actions address public pauseGuardian; // On upgrades this is set in the case that the pause router is used to pass the rollback check address internal rollbackRouterImplementation; // A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user // to set an allowance on all nTokens for a particular integrating contract system. // owner => spender => transferAllowance mapping(address => mapping(address => uint256)) internal nTokenWhitelist; // Individual transfer allowances for nTokens used for ERC20 // owner => spender => currencyId => transferAllowance mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance; // Transfer operators // Mapping from a global ERC1155 transfer operator contract to an approval value for it mapping(address => bool) internal globalTransferOperator; // Mapping from an account => operator => approval status for that operator. This is a specific // approval between two addresses for ERC1155 transfers. mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator; // Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in // BatchAction.sol, can only be set by governance mapping(address => bool) internal authorizedCallbackContract; // Reverse mapping from token addresses to currency ids, only used for referencing in views // and checking for duplicate token listings. mapping(address => uint16) internal tokenAddressToCurrencyId; // Reentrancy guard uint256 internal reentrancyStatus; }
Returns a currency and its corresponding asset rate and ETH exchange rates. Note that this does not recalculate cToken interest rates, it only retrieves the latest stored rate.
function getCurrencyAndRates(uint16 currencyId) external view override returns ( Token memory assetToken, Token memory underlyingToken, ETHRate memory ethRate, AssetRateParameters memory assetRate ) { _checkValidCurrency(currencyId); assetToken = TokenHandler.getAssetToken(currencyId); underlyingToken = TokenHandler.getUnderlyingToken(currencyId); ethRate = ExchangeRate.buildExchangeRate(currencyId); assetRate = AssetRate.buildAssetRateView(currencyId); }
5,901,869
./partial_match/1/0x9C1b2F065CE61904F15C0F7d86b66b57B3745d09/sources/BBC.sol
Set maximum transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = _tTotal*maxTxAmount/100; require (_maxTxAmount >= _tTotal/100 ,"Max Tx must be more than 1%"); }
16,034,045
pragma solidity ^0.5.3; pragma experimental ABIEncoderV2; import "./IPoMain.sol"; import "./IPoTypes.sol"; import "./IErc20.sol"; import "./IPoStorage.sol"; import "./IProductStorage.sol"; import "./IBusinessPartnerStorage.sol"; import "./IFunding.sol"; import "./IWalletBuyer.sol"; import "./IWalletSeller.sol"; import "./IAddressRegistry.sol"; import "./Debuggable.sol"; /// @title Purchasing Main Contract /// @notice Create or change a purchase order, pulling funds as required (funds should be approved before calling here). contract PoMain is IPoMain, Debuggable { // Mainly Seller facing event PurchaseRaisedOkLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event PurchaseCancelRequestedOkLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); // Mainly Buyer facing event PurchaseCancelSucceededLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event PurchaseCancelFailedLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event PurchaseUpdatedWithSalesOrderOkLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event SalesOrderCancelFailedLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event SalesOrderNotApprovedLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event SalesOrderInvoiceFault(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); // Buyer and Seller facing payment related event PurchasePaymentMadeOkLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event PurchasePaymentFailedLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event PurchaseRefundMadeOkLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event PurchaseRefundFailedLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); // Debug event PurchaseDataInLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); event PurchaseOrderSnapshotLog(bytes32 indexed buyerSysId, bytes32 indexed sellerSysId, uint64 indexed ethPurchaseOrderNumber, IPoTypes.Po po); IPoStorage public poStorage; IProductStorage public productStorage; IBusinessPartnerStorage public businessPartnerStorage; IFunding public fundingContract; IAddressRegistry public addressRegistry; constructor (address contractAddressOfRegistry) public payable { addressRegistry = IAddressRegistry(contractAddressOfRegistry); } /// @title Configure contract /// @param nameOfPoStorage key of the entry in the address registry that holds the PO storage contract address /// @param nameOfProductStorage key of the entry in the address registry that holds the product storage contract address /// @param nameOfBusinessPartnerStorage key of the entry in the address registry that holds the business partner storage contract address /// @param nameOfFundingContract key of the entry in the address registry that holds the funding contract address function configure(string memory nameOfPoStorage, string memory nameOfProductStorage, string memory nameOfBusinessPartnerStorage, string memory nameOfFundingContract) public { // Po Storage poStorage = IPoStorage(addressRegistry.getAddressString(nameOfPoStorage)); require(address(poStorage) != address(0), "Could not find PoStorage address in registry"); // Product Storage productStorage = IProductStorage(addressRegistry.getAddressString(nameOfProductStorage)); require(address(productStorage) != address(0), "Could not find ProductStorage address in registry"); // Business Partner Storage businessPartnerStorage = IBusinessPartnerStorage(addressRegistry.getAddressString(nameOfBusinessPartnerStorage)); require(address(businessPartnerStorage) != address(0), "Could not find BusinessPartnerStorage address in registry"); // Funding Contract fundingContract = IFunding(addressRegistry.getAddressString(nameOfFundingContract)); require(address(fundingContract) != address(0), "Could not find FundingContract address in registry"); } /// @title Make a purchase as specified by po. Critical fields for this fn: /// @param po.currencyAddress: address of an ERC20 that has already approved us some funds /// @param po.totalValue: token quantity in its base integer unit /// @return requestSuccessful true means the request for creation was made successfully (not that the creation itself was successful, this is still unknown) /// @dev must be called by wallet of buyer system (only they have auths to raise a PO for their own system) function createPurchaseOrder(IPoTypes.Po memory po) public returns (bool requestSuccessful) { // Debug, record PO data exactly as we received it emit PurchaseDataInLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); // Po Validation // Ensure buyer told us who they are //require(po.buyerSysId.length > 0, "Buyer Id must be specified"); logDebugBytes32("Buyer id:", po.buyerSysId); // Ensure buyer really is who they say they are (tx must come from buyer wallet address) address buyerWalletShouldBe = businessPartnerStorage.getWalletAddress(po.buyerSysId); //require(msg.sender == buyerWalletShouldBe, "Function must be called from Buyer Wallet"); logDebugBytes32("Buyer sys id:", po.buyerSysId); logDebugAddr("Buyer wallet should be:", buyerWalletShouldBe); logDebugAddr("msg.sender:", msg.sender); // Ensure buyer chose a seller //require(po.sellerSysId.length > 0, "Seller Id must be specified"); logDebugBytes32("Seller id:", po.sellerSysId); // TODO validate product IDs here // Globally unique Eth PO number po.ethPurchaseOrderNumber = poStorage.getNextPoNumber(); logDebugUint64("Next PO number:", po.ethPurchaseOrderNumber); // Map buyer system id to a customer number in the seller system po.sellerViewCustomerId = businessPartnerStorage.getSellerViewCustomerIdForBuyerSysId(po.buyerSysId, po.sellerSysId); logDebugBytes32("Customer id:", po.sellerViewCustomerId); // Map seller system id to a vendor number in the buyer system (may be needed if buyer system is ERP, returns initial value if not configured) po.buyerViewVendorId = businessPartnerStorage.getBuyerViewVendorIdForSellerSysId(po.buyerSysId, po.sellerSysId); logDebugBytes32("Vendor id:", po.buyerViewVendorId); // Map product id from buyer id to seller id po.sellerProductId = productStorage.getSellerProductIdForBuyerProductId(po.buyerSysId, po.buyerProductId, po.sellerSysId); logDebugBytes32("Seller Product id:", po.sellerProductId); // Qty value po.openInvoiceQuantity = po.totalQuantity; po.openInvoiceValue = po.totalValue; // po.tokenId = uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, po.ethPurchaseOrderNumber, po.sellerProductId, po.totalQuantity))); // Statuses po.poStatus = IPoTypes.PoStatus.PurchaseOrderCreated; // Contract controlled status po.wiProcessStatus = IPoTypes.WiProcessStatus.Empty; // Mirror of work item process status from app // Store Po details in eternal storage poStorage.setPo(po); logDebugString("PO storage ok"); // Funding. Here, the Funding contract attempts to pull in funds from buyer wallet fundingContract.transferInFundsForPoFromBuyer(po.ethPurchaseOrderNumber); logDebugString("Call funding ok"); bool isFunded = fundingContract.getPoFundingStatus(po.ethPurchaseOrderNumber); //require(isFunded == true, "Insufficient funding for PO"); if (isFunded) { logDebugString("PO funded ok"); } else { logDebugString("PO not funded"); } // Events requestSuccessful = true; emit PurchaseRaisedOkLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); // Inform seller wallet address walletSellerAddress = businessPartnerStorage.getWalletAddress(po.sellerSysId); require(walletSellerAddress != address(0), "Could not find wallet seller address in business partner storage"); IWalletSeller walletSeller = IWalletSeller(walletSellerAddress); walletSeller.onCreatePurchaseOrderRequested(po); } function cancelPurchaseOrder(uint64 ethPoNumber) external returns (bool requestSuccessful) { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); // Tx must come from buyer wallet address address buyerWalletShouldBe = businessPartnerStorage.getWalletAddress(po.buyerSysId); require(msg.sender == buyerWalletShouldBe, "Function must be called from Buyer Wallet"); requestSuccessful = true; emit PurchaseCancelRequestedOkLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); // Inform seller Wallet address walletSellerAddress = businessPartnerStorage.getWalletAddress(po.sellerSysId); require(walletSellerAddress != address(0), "Could not find wallet seller address in registry"); IWalletSeller walletSeller = IWalletSeller(walletSellerAddress); walletSeller.onCancelPurchaseOrderRequested(po); } /// @dev Update the PO with the given sales order /// @dev must be called by wallet of seller system (only they have auths to add a sales order) function setSalesOrderNumberByEthPoNumber(uint64 ethPoNumber, bytes32 sellerSysId, bytes32 sellerSalesOrderNumber) public { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); // Ensure seller really is who they say they are (tx must come from seller wallet address) address sellerWalletShouldBe = businessPartnerStorage.getWalletAddress(po.sellerSysId); require(msg.sender == sellerWalletShouldBe, "Function must be called from Seller Wallet"); po.sellerSysId = sellerSysId; po.sellerSalesOrderNumber = sellerSalesOrderNumber; po.poStatus = IPoTypes.PoStatus.SalesOrderNumberReceived; poStorage.setPo(po); emit PurchaseUpdatedWithSalesOrderOkLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); // Inform buyer wallet address walletBuyerAddress = businessPartnerStorage.getWalletAddress(po.buyerSysId); require(walletBuyerAddress != address(0), "Could not find wallet buyer address in business partner storage"); IWalletBuyer walletBuyer = IWalletBuyer(walletBuyerAddress); walletBuyer.onPurchaseUpdatedWithSalesOrder(po); } function getSalesOrderNumberByEthPoNumber(uint64 ethPoNumber) public view returns (bytes32 sellerSysId, bytes32 sellerSalesOrderNumber) { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); return (po.sellerSysId, po.sellerSalesOrderNumber); } /// @dev pass-through to po storage function getSalesOrderNumberByBuyerPoNumber(bytes32 buyerSystemId, bytes32 buyerPoNumber) public view returns (bytes32 sellerSysId, bytes32 sellerSalesOrderNumber) { IPoTypes.Po memory po = poStorage.getPoByBuyerPoNumber(buyerSystemId, buyerPoNumber); return (po.sellerSysId, po.sellerSalesOrderNumber); } /// @dev pass-through to po storage function getPoByEthPoNumber(uint64 ethPoNumber) public view returns (IPoTypes.Po memory po) { return poStorage.getPoByEthPoNumber(ethPoNumber); } /// @dev pass-through to po storage function getPoByBuyerPoNumber(bytes32 buyerSystemId, bytes32 buyerPoNumber) public view returns (IPoTypes.Po memory po) { return poStorage.getPoByBuyerPoNumber(buyerSystemId, buyerPoNumber); } /// @dev writes a snapshot of the PO to event log, for debugging function writePoToEventLog(uint64 ethPoNumber) external { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); emit PurchaseOrderSnapshotLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); } /// @dev pass-through to po storage function getLatestPoNumber() external view returns (uint64 poNumber) { return poStorage.getCurrentPoNumber(); } /// @dev must be called by wallet of seller system (only they have auths to refund money) function refundPoToBuyer(uint64 ethPoNumber) public { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); // Ensure seller really is who they say they are (tx must come from seller wallet address) address sellerWalletShouldBe = businessPartnerStorage.getWalletAddress(po.sellerSysId); require(msg.sender == sellerWalletShouldBe, "Function must be called from Seller Wallet"); // Ensure PO is in suitable state require(po.poStatus != IPoTypes.PoStatus.Completed, "PO must not be completed"); require(po.poStatus != IPoTypes.PoStatus.Cancelled, "PO must not be cancelled"); // Prepare to inform buyer wallet of result address walletBuyerAddress = businessPartnerStorage.getWalletAddress(po.buyerSysId); IWalletBuyer walletBuyer = IWalletBuyer(walletBuyerAddress); // Refund bool isFunded = fundingContract.getPoFundingStatus(po.ethPurchaseOrderNumber); if (isFunded) { fundingContract.transferOutFundsForPoToBuyer(po.ethPurchaseOrderNumber); po.poStatus = IPoTypes.PoStatus.Cancelled; poStorage.setPo(po); emit PurchaseRefundMadeOkLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); walletBuyer.onPurchaseRefundMadeOk(po); } else { // Cannot refund to buyer emit PurchaseRefundFailedLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); walletBuyer.onPurchaseRefundFailed(po); } } /// @dev must be called by wallet of seller system function releasePoFundsToSeller(uint64 ethPoNumber) public { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); // Ensure seller really is who they say they are (tx must come from seller wallet address) address sellerWalletShouldBe = businessPartnerStorage.getWalletAddress(po.sellerSysId); require(msg.sender == sellerWalletShouldBe, "Function must be called from Seller Wallet"); // Ensure PO is in suitable state require(po.poStatus == IPoTypes.PoStatus.SalesOrderNumberReceived, "PO must have SO"); // Prepare to inform buyer wallet of result address walletBuyerAddress = businessPartnerStorage.getWalletAddress(po.buyerSysId); IWalletBuyer walletBuyer = IWalletBuyer(walletBuyerAddress); // Try to release the funds bool isFunded = fundingContract.getPoFundingStatus(po.ethPurchaseOrderNumber); if (isFunded) { fundingContract.transferOutFundsForPoToSeller(po.ethPurchaseOrderNumber); po.poStatus = IPoTypes.PoStatus.Completed; poStorage.setPo(po); emit PurchasePaymentMadeOkLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); walletBuyer.onPurchasePaymentMadeOk(po); } else { // Cannot release funds to seller emit PurchasePaymentFailedLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); walletBuyer.onPurchasePaymentFailed(po); } } function reportSalesOrderNotApproved(uint64 ethPoNumber) external { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); // Ensure seller really is who they say they are (tx must come from seller wallet address) address sellerWalletShouldBe = businessPartnerStorage.getWalletAddress(po.sellerSysId); require(msg.sender == sellerWalletShouldBe, "Function must be called from Seller Wallet"); emit SalesOrderNotApprovedLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); // Inform buyer wallet address walletBuyerAddress = businessPartnerStorage.getWalletAddress(po.buyerSysId); IWalletBuyer walletBuyer = IWalletBuyer(walletBuyerAddress); walletBuyer.onSalesOrderNotApproved(po); } function reportSalesOrderCancelFailure(uint64 ethPoNumber) external { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); // Ensure seller really is who they say they are (tx must come from seller wallet address) address sellerWalletShouldBe = businessPartnerStorage.getWalletAddress(po.sellerSysId); require(msg.sender == sellerWalletShouldBe, "Function must be called from Seller Wallet"); emit SalesOrderCancelFailedLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); // Inform buyer wallet address walletBuyerAddress = businessPartnerStorage.getWalletAddress(po.buyerSysId); IWalletBuyer walletBuyer = IWalletBuyer(walletBuyerAddress); walletBuyer.onSalesOrderCancelFailure(po); } function reportSalesOrderInvoiceFault(uint64 ethPoNumber) external { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); // Ensure seller really is who they say they are (tx must come from seller wallet address) address sellerWalletShouldBe = businessPartnerStorage.getWalletAddress(po.sellerSysId); require(msg.sender == sellerWalletShouldBe, "Function must be called from Seller Wallet"); emit SalesOrderInvoiceFault(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); // Inform buyer wallet address walletBuyerAddress = businessPartnerStorage.getWalletAddress(po.buyerSysId); IWalletBuyer walletBuyer = IWalletBuyer(walletBuyerAddress); walletBuyer.onSalesOrderInvoiceFault(po); } }
writes a snapshot of the PO to event log, for debugging
function writePoToEventLog(uint64 ethPoNumber) external { IPoTypes.Po memory po = poStorage.getPoByEthPoNumber(ethPoNumber); emit PurchaseOrderSnapshotLog(po.buyerSysId, po.sellerSysId, po.ethPurchaseOrderNumber, po); }
12,594,554
pragma solidity ^0.5.1; import "../../lib/lifecycle/Destructible.sol"; import "../../lib/ownership/Upgradable.sol"; import "../../lib/ERC20.sol"; import "../database/DatabaseInterface.sol"; import "./currentCost/CurrentCostInterface.sol"; import "./BondageInterface.sol"; import "../../hardhat/console.sol"; contract Bondage is Destructible, BondageInterface, Upgradable { DatabaseInterface public db; event Bound(address indexed holder, address indexed oracle, bytes32 indexed endpoint, uint256 numZap, uint256 numDots); event Unbound(address indexed holder, address indexed oracle, bytes32 indexed endpoint, uint256 numDots); event Escrowed(address indexed holder, address indexed oracle, bytes32 indexed endpoint, uint256 numDots); event Released(address indexed holder, address indexed oracle, bytes32 indexed endpoint, uint256 numDots); event Returned(address indexed holder, address indexed oracle, bytes32 indexed endpoint, uint256 numDots); CurrentCostInterface currentCost; ERC20 token; address public arbiterAddress; address public dispatchAddress; // For restricting dot escrow/transfer method calls to Dispatch and Arbiter modifier operatorOnly() { require(msg.sender == arbiterAddress || msg.sender == dispatchAddress, "Error: Operator Only Error"); _; } /// @dev Initialize Storage, Token, and CurrentCost Contracts constructor(address c) Upgradable(c) public { _updateDependencies(); } function _updateDependencies() internal { address databaseAddress = coordinator.getContract("DATABASE"); db = DatabaseInterface(databaseAddress); arbiterAddress = coordinator.getContract("ARBITER"); dispatchAddress = coordinator.getContract("DISPATCH"); token = ERC20(coordinator.getContract("ZAP_TOKEN")); currentCost = CurrentCostInterface(coordinator.getContract("CURRENT_COST")); } /// @dev will bond to an oracle /// @return total ZAP bound to oracle function bond(address oracleAddress, bytes32 endpoint, uint256 numDots) external returns (uint256 bound) { bound = _bond(msg.sender, oracleAddress, endpoint, numDots); emit Bound(msg.sender, oracleAddress, endpoint, bound, numDots); } /// @return total ZAP unbound from oracle function unbond(address oracleAddress, bytes32 endpoint, uint256 numDots) external returns (uint256 unbound) { unbound = _unbond(msg.sender, oracleAddress, endpoint, numDots); emit Unbound(msg.sender, oracleAddress, endpoint, numDots); } /// @dev will bond to an oracle on behalf of some holder /// @return total ZAP bound to oracle function delegateBond(address holderAddress, address oracleAddress, bytes32 endpoint, uint256 numDots) external returns (uint256 boundZap) { boundZap = _bond(holderAddress, oracleAddress, endpoint, numDots); emit Bound(holderAddress, oracleAddress, endpoint, boundZap, numDots); } /// @dev Move numDots dots from provider-requester to bondage according to /// data-provider address, holder address, and endpoint specifier (ala 'smart_contract') /// Called only by Dispatch or Arbiter Contracts function escrowDots( address holderAddress, address oracleAddress, bytes32 endpoint, uint256 numDots ) external operatorOnly returns (bool success) { uint256 boundDots = getBoundDots(holderAddress, oracleAddress, endpoint); require(numDots <= boundDots, "Error: Not enough dots bound"); updateEscrow(holderAddress, oracleAddress, endpoint, numDots, "add"); updateBondValue(holderAddress, oracleAddress, endpoint, numDots, "sub"); emit Escrowed(holderAddress, oracleAddress, endpoint, numDots); return true; } /// @dev Transfer N dots from fromAddress to destAddress. /// Called only by Disptach or Arbiter Contracts /// In smart contract endpoint, occurs per satisfied request. /// In socket endpoint called on termination of subscription. function releaseDots( address holderAddress, address oracleAddress, bytes32 endpoint, uint256 numDots ) external operatorOnly returns (bool success) { uint256 numEscrowed = getNumEscrow(holderAddress, oracleAddress, endpoint); require(numDots <= numEscrowed, "Error: Not enough dots Escrowed"); updateEscrow(holderAddress, oracleAddress, endpoint, numDots, "sub"); updateBondValue(oracleAddress, oracleAddress, endpoint, numDots, "add"); emit Released(holderAddress, oracleAddress, endpoint, numDots); return true; } /// @dev Transfer N dots from destAddress to fromAddress. /// Called only by Disptach or Arbiter Contracts /// In smart contract endpoint, occurs per satisfied request. /// In socket endpoint called on termination of subscription. function returnDots( address holderAddress, address oracleAddress, bytes32 endpoint, uint256 numDots ) external operatorOnly returns (bool success) { uint256 numEscrowed = getNumEscrow(holderAddress, oracleAddress, endpoint); require(numDots <= numEscrowed, "Error: Not enough dots escrowed"); updateEscrow(holderAddress, oracleAddress, endpoint, numDots, "sub"); updateBondValue(holderAddress, oracleAddress, endpoint, numDots, "add"); emit Returned(holderAddress, oracleAddress, endpoint, numDots); return true; } /// @dev Calculate quantity of tokens required for specified amount of dots /// for endpoint defined by endpoint and data provider defined by oracleAddress function calcZapForDots( address oracleAddress, bytes32 endpoint, uint256 numDots ) external view returns (uint256 numZap) { uint256 issued = getDotsIssued(oracleAddress, endpoint); return currentCost._costOfNDots(oracleAddress, endpoint, issued + 1, numDots - 1); } /// @dev Get the current cost of a dot. /// @param endpoint specifier /// @param oracleAddress data-provider /// @param totalBound current number of dots function currentCostOfDot( address oracleAddress, bytes32 endpoint, uint256 totalBound ) public view returns (uint256 cost) { return currentCost._currentCostOfDot(oracleAddress, endpoint, totalBound); } /// @dev Get issuance limit of dots /// @param endpoint specifier /// @param oracleAddress data-provider function dotLimit( address oracleAddress, bytes32 endpoint ) public view returns (uint256 limit) { return currentCost._dotLimit(oracleAddress, endpoint); } /// @return total ZAP held by contract function getZapBound(address oracleAddress, bytes32 endpoint) public view returns (uint256) { return getNumZap(oracleAddress, endpoint); } function _bond( address holderAddress, address oracleAddress, bytes32 endpoint, uint256 numDots ) private returns (uint256) { address broker = getEndpointBroker(oracleAddress, endpoint); console.log(broker); console.log("the broker"); if (broker != address(0)) { require(msg.sender == broker, "Error: Only the broker has access to this function"); } // This also checks if oracle is registered w/ an initialized curve uint256 issued = getDotsIssued(oracleAddress, endpoint); require(issued + numDots <= dotLimit(oracleAddress, endpoint), "Error: Dot limit exceeded"); uint256 numZap = currentCost._costOfNDots(oracleAddress, endpoint, issued + 1, numDots - 1); // User must have approved contract to transfer working ZAP require(token.transferFrom(msg.sender, address(this), numZap), "Error: User must have approved contract to transfer ZAP"); if (!isProviderInitialized(holderAddress, oracleAddress)) { setProviderInitialized(holderAddress, oracleAddress); addHolderOracle(holderAddress, oracleAddress); } updateBondValue(holderAddress, oracleAddress, endpoint, numDots, "add"); updateTotalIssued(oracleAddress, endpoint, numDots, "add"); updateTotalBound(oracleAddress, endpoint, numZap, "add"); return numZap; } function _unbond( address holderAddress, address oracleAddress, bytes32 endpoint, uint256 numDots ) private returns (uint256 numZap) { address broker = getEndpointBroker(oracleAddress, endpoint); if (broker != address(0)) { require(msg.sender == broker, "Error: Only the broker has access to this function"); } // Make sure the user has enough to bond with some additional sanity checks uint256 amountBound = getBoundDots(holderAddress, oracleAddress, endpoint); require(amountBound >= numDots, "Error: Not enough dots bonded"); require(numDots > 0, "Error: Dots to unbond must be more than zero"); // Get the value of the dots uint256 issued = getDotsIssued(oracleAddress, endpoint); numZap = currentCost._costOfNDots(oracleAddress, endpoint, issued + 1 - numDots, numDots - 1); // Update the storage values updateTotalBound(oracleAddress, endpoint, numZap, "sub"); updateTotalIssued(oracleAddress, endpoint, numDots, "sub"); updateBondValue(holderAddress, oracleAddress, endpoint, numDots, "sub"); // Do the transfer require(token.transfer(msg.sender, numZap), "Error: Transfer failed"); return numZap; } /**** Get Methods ****/ function isProviderInitialized(address holderAddress, address oracleAddress) public view returns (bool) { return db.getNumber(keccak256(abi.encodePacked('holders', holderAddress, 'initialized', oracleAddress))) == 1 ? true : false; } /// @dev get broker address for endpoint function getEndpointBroker(address oracleAddress, bytes32 endpoint) public view returns (address) { // bytes32 result=db.getBytes32(keccak256(abi.encodePacked('oracles', oracleAddress, endpoint, 'broker'))); return address(uint160(bytes20(db.getBytes32(keccak256(abi.encodePacked('oracles', oracleAddress, endpoint, 'broker')))))); } function getNumEscrow(address holderAddress, address oracleAddress, bytes32 endpoint) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('escrow', holderAddress, oracleAddress, endpoint))); } function getNumZap(address oracleAddress, bytes32 endpoint) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('totalBound', oracleAddress, endpoint))); } function getDotsIssued(address oracleAddress, bytes32 endpoint) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('totalIssued', oracleAddress, endpoint))); } function getBoundDots(address holderAddress, address oracleAddress, bytes32 endpoint) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('holders', holderAddress, 'bonds', oracleAddress, endpoint))); } function getIndexSize(address holderAddress) external view returns (uint256) { return db.getAddressArrayLength(keccak256(abi.encodePacked('holders', holderAddress, 'oracleList'))); } function getOracleAddress(address holderAddress, uint256 index) public view returns (address) { return db.getAddressArrayIndex(keccak256(abi.encodePacked('holders', holderAddress, 'oracleList')), index); } /**** Set Methods ****/ function addHolderOracle(address holderAddress, address oracleAddress) internal { db.pushAddressArray(keccak256(abi.encodePacked('holders', holderAddress, 'oracleList')), oracleAddress); } function setProviderInitialized(address holderAddress, address oracleAddress) internal { db.setNumber(keccak256(abi.encodePacked('holders', holderAddress, 'initialized', oracleAddress)), 1); } function updateEscrow(address holderAddress, address oracleAddress, bytes32 endpoint, uint256 numDots, bytes32 op) internal { uint256 newEscrow = db.getNumber(keccak256(abi.encodePacked('escrow', holderAddress, oracleAddress, endpoint))); if (op == "sub") { newEscrow -= numDots; } else if (op == "add") { newEscrow += numDots; } else { revert(); } db.setNumber(keccak256(abi.encodePacked('escrow', holderAddress, oracleAddress, endpoint)), newEscrow); } function updateBondValue(address holderAddress, address oracleAddress, bytes32 endpoint, uint256 numDots, bytes32 op) internal { uint256 bondValue = db.getNumber(keccak256(abi.encodePacked('holders', holderAddress, 'bonds', oracleAddress, endpoint))); if (op == "sub") { bondValue -= numDots; } else if (op == "add") { bondValue += numDots; } db.setNumber(keccak256(abi.encodePacked('holders', holderAddress, 'bonds', oracleAddress, endpoint)), bondValue); } function updateTotalBound(address oracleAddress, bytes32 endpoint, uint256 numZap, bytes32 op) internal { uint256 totalBound = db.getNumber(keccak256(abi.encodePacked('totalBound', oracleAddress, endpoint))); if (op == "sub"){ totalBound -= numZap; } else if (op == "add") { totalBound += numZap; } else { revert(); } db.setNumber(keccak256(abi.encodePacked('totalBound', oracleAddress, endpoint)), totalBound); } function updateTotalIssued(address oracleAddress, bytes32 endpoint, uint256 numDots, bytes32 op) internal { uint256 totalIssued = db.getNumber(keccak256(abi.encodePacked('totalIssued', oracleAddress, endpoint))); if (op == "sub"){ totalIssued -= numDots; } else if (op == "add") { totalIssued += numDots; } else { revert(); } db.setNumber(keccak256(abi.encodePacked('totalIssued', oracleAddress, endpoint)), totalIssued); } } /*************************************** STORAGE **************************************** * 'holders', holderAddress, 'initialized', oracleAddress => {uint256} 1 -> provider-subscriber initialized, 0 -> not initialized * 'holders', holderAddress, 'bonds', oracleAddress, endpoint => {uint256} number of dots this address has bound to this endpoint * 'oracles', oracleAddress, endpoint, 'broker' => {address} address of endpoint broker, 0 if none * 'escrow', holderAddress, oracleAddress, endpoint => {uint256} amount of Zap that have been escrowed * 'totalBound', oracleAddress, endpoint => {uint256} amount of Zap bound to this endpoint * 'totalIssued', oracleAddress, endpoint => {uint256} number of dots issued by this endpoint * 'holders', holderAddress, 'oracleList' => {address[]} array of oracle addresses associated with this holder ****************************************************************************************/
Calculate quantity of tokens required for specified amount of dots for endpoint defined by endpoint and data provider defined by oracleAddress
function calcZapForDots( address oracleAddress, bytes32 endpoint, uint256 numDots ) external view returns (uint256 numZap) { uint256 issued = getDotsIssued(oracleAddress, endpoint); return currentCost._costOfNDots(oracleAddress, endpoint, issued + 1, numDots - 1); }
6,387,855
/** *Submitted for verification at Etherscan.io on 2022-01-22 */ // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/HSPPG.sol pragma solidity >=0.7.0 <0.9.0; // This for the Sauce ERC-20 Reward Tokens interface SauceToken { function balanceOf(address owner) external view returns (uint256 balance); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } contract HSPP is ERC721Enumerable, Ownable { using Strings for uint256; address private MixContract; string _baseTokenURI; string public baseExtension = ".json"; uint256 public _maxperTX = 3; // Max per mint uint256 public _maxperWalletWaitList = 1; // Waitlist max mint per wallet uint256 public _maxperWalletMint = 3; // Mint max Mint per wallet uint256 public _limit = 100; // Supply of token uint256 public _price = 0.2 ether; // Price uint256 public waitlist_count = 0; // Start count for waitlist address public fundWallet; // Fund Wallet bool public _presaleWLPaused = true; // Contract is paused bool public _PublicPaused = true; // Contract is paused mapping (address => uint256) public perWallet; // Mapping per wallet mapping (address => bool) public waitlist; // Mapping per waitlist SauceToken public TokenContract; // Token functions address payable public payments; // Payable bool public isBurningActive = false; // Paused for Burning Function // Constructor for the token constructor(string memory initbaseURI, address _fundWallet) ERC721("HS Pepper Party Genesis", "HSPP") { require(_fundWallet != address(0), "Zero address error"); setBaseURI(initbaseURI); fundWallet = _fundWallet; } // Internal URI function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } // Token Public only owner functions function setSauceToken (SauceToken _TokenContract) public onlyOwner{ // require(_TokenContract != address(0), "Contract address can't be zero address"); TokenContract = _TokenContract; } // Public view token function getSauceToken(address __address) public view returns(uint256) { require(__address != address(0), "Contract address can't be zero address"); return TokenContract.balanceOf(__address); } // Get Allowance public view function getSauceAllowance(address __address) public view returns(uint256) { require(__address != address(0), "Contract address can't be zero address"); return TokenContract.allowance(__address, address(this)); } // Mint Function public payable function MINT(uint256 num) public payable { uint256 supply = totalSupply(); require( !_PublicPaused, "Sale paused" ); require( num <= _maxperTX, "You are exceeding limit of per transaction TLM" ); require( perWallet[msg.sender] + num <= _maxperWalletMint, "You are exceeding limit of per wallet TLM" ); require( num > 0); require( supply + num <= _limit, "Exceeds maximum HSPP supply" ); require( msg.value >= _price * num, "Ether sent is not correct" ); for(uint256 i = 1 ; i <= num; i++){ _safeMint( msg.sender, supply + i ); } perWallet[msg.sender] += num; } // Mint Function external onlyOwner function mintForAddress(address _to, uint256 _amount) external onlyOwner() { require( _to != address(0), "Zero address error"); require( _amount <= _limit, "Exceeds Limit supply"); uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( _to, supply + i ); } _limit -= _amount; } // Internal memory with public view for the wallet of owner function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } // Waitlist Mint public payable only for the waitlisted people function WAITLIST_MINT(uint256 num) public payable { uint256 supply = totalSupply(); require( !_presaleWLPaused, "Sale paused" ); require( waitlist[msg.sender] == true, "Only WAITLIST can mint" ); require( perWallet[msg.sender] + num <= _maxperWalletWaitList, "You are exceeding limit of per wallet HSPP" ); require( supply + num <= _limit, "Exceeds maximum HSPP supply" ); require( msg.value >= _price * num, "Ether sent is not correct" ); for(uint256 i; i < num; i++){ _safeMint( msg.sender, supply + i ); } perWallet[msg.sender] += num; } // Bulk Waitlist wallets function bulk_waitlist(address[] memory addresses) public onlyOwner() { for(uint i=0; i < addresses.length; i++){ address addr = addresses[i]; if(waitlist[addr] != true && addr != address(0)){ waitlist[addr] = true; waitlist_count++; } } } // Function remove Waitlist wallet / only owner function remove_waitlist(address _address) public onlyOwner() { require(_address != address(0), "Zero address error"); waitlist[_address] = false; waitlist_count--; } // Just in case Eth does some crazy stuff ( Change price ) only owner function setPrice(uint256 _newPrice) public onlyOwner() { _price = _newPrice; } // Set FundWallet function setFundWallet(address _fundWallet) public onlyOwner() { require(_fundWallet != address(0), "Zero address error"); fundWallet = _fundWallet; } // Max per wallet function setMaxPerWallet(uint256 limit) public onlyOwner { _maxperTX = limit; } // Token URI function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseTokenURI = _baseURI(); return bytes(currentBaseTokenURI).length > 0 ? string(abi.encodePacked(currentBaseTokenURI, tokenId.toString(), baseExtension)) : ""; } // Burn Function used for the HSPP Kitchen function burnForMint(uint256 _tokenId) public { require(isBurningActive, "Burning not active"); require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // Pause Burn function toggleBurningActive() public onlyOwner { isBurningActive = !isBurningActive; } // Price Show Public function getPrice() public view returns (uint256){ return _price; } // Public Set URI if Needed function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } // Pause Contract public only owner function PublicPaused() public onlyOwner { _PublicPaused = !_PublicPaused; } // Pause Contract presaleWL only owner function presaleWLPaused() public onlyOwner { _presaleWLPaused = !_presaleWLPaused; } // Withdraw Fund function withdrawAll() public payable onlyOwner { require(payable(fundWallet).send(address(this).balance)); } }
Pause Contract presaleWL only owner
function presaleWLPaused() public onlyOwner { _presaleWLPaused = !_presaleWLPaused; }
14,966,410
// SPDX-License-Identifier: MIT pragma solidity ^0.6.2; // interface IERC20 { function TOTALSUPPLY709() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF1000(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER912(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE378(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM696(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER249(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL928(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // abstract contract Context { function _MSGSENDER905() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA980() 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; } } // contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED618(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER905(); _owner = msgSender; emit OWNERSHIPTRANSFERRED618(address(0), msgSender); } function OWNER941() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER378() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER905(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP149() public virtual ONLYOWNER378 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED618(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP687(address newOwner) public virtual ONLYOWNER378 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED618(_owner, newOwner); _owner = newOwner; } } // library SafeMath { function ADD236(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB786(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB786(a, b, "SafeMath: subtraction overflow"); } function SUB786(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 MUL747(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 DIV140(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV140(a, b, "SafeMath: division by zero"); } function DIV140(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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 MOD599(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD599(a, b, "SafeMath: modulo by zero"); } function MOD599(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // library Address { function ISCONTRACT863(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function SENDVALUE275(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL887(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL887(target, data, "Address: low-level call failed"); } function FUNCTIONCALL887(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE192(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE672(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE672(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE672(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE192(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE192(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT863(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // contract 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_entered586 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered769 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered586; } modifier NONREENTRANT44() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered769, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered769; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered586; } } // library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER115(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.TRANSFER912.selector, to, value)); } function SAFETRANSFERFROM287(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.TRANSFERFROM696.selector, from, to, value)); } function SAFEAPPROVE190(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE643(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, value)); } function SAFEINCREASEALLOWANCE374(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE643(address(this), spender).ADD236(value); _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE80(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE643(address(this), spender).SUB786(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN516(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).FUNCTIONCALL887(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"); } } } // 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME654() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL381() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS442() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY709() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF1000(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER912(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER205(_MSGSENDER905(), recipient, amount); return true; } function ALLOWANCE643(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE378(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE516(_MSGSENDER905(), spender, amount); return true; } function TRANSFERFROM696(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER205(sender, recipient, amount); _APPROVE516(sender, _MSGSENDER905(), _allowances[sender][_MSGSENDER905()].SUB786(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE9(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE516(_MSGSENDER905(), spender, _allowances[_MSGSENDER905()][spender].ADD236(addedValue)); return true; } function DECREASEALLOWANCE999(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE516(_MSGSENDER905(), spender, _allowances[_MSGSENDER905()][spender].SUB786(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER205(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER183(sender, recipient, amount); _balances[sender] = _balances[sender].SUB786(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD236(amount); emit TRANSFER249(sender, recipient, amount); } function _MINT985(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER183(address(0), account, amount); _totalSupply = _totalSupply.ADD236(amount); _balances[account] = _balances[account].ADD236(amount); emit TRANSFER249(address(0), account, amount); } function _BURN126(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER183(account, address(0), amount); _balances[account] = _balances[account].SUB786(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB786(amount); emit TRANSFER249(account, address(0), amount); } function _APPROVE516(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL928(owner, spender, amount); } function _SETUPDECIMALS502(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER183(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } // contract YieldDelegatingVaultEvent2 { event NEWTREASURY741(address oldTreasury, address newTreasury); //inject NONSTANDARD NAMING event NEWDELEGATEPERCENT315(uint256 oldDelegatePercent, uint256 newDelegatePercent); //inject NONSTANDARD NAMING event NEWREWARDPERTOKEN257(uint256 oldRewardPerToken, uint256 newRewardPerToken); //inject NONSTANDARD NAMING } // 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; } function _ADD330(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS441(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; } } function _REMOVE267(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS441(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH266(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT20(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD236(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD330(set._inner, bytes32(uint256(value))); } function REMOVE884(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE267(set._inner, bytes32(uint256(value))); } function CONTAINS556(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS441(set._inner, bytes32(uint256(value))); } function LENGTH118(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH266(set._inner); } function AT34(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT20(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD236(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD330(set._inner, bytes32(value)); } function REMOVE884(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE267(set._inner, bytes32(value)); } function CONTAINS556(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS441(set._inner, bytes32(value)); } function LENGTH118(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH266(set._inner); } function AT34(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT20(set._inner, index)); } } // 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_role567 = 0x00; //inject NONSTANDARD NAMING event ROLEADMINCHANGED88(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING event ROLEGRANTED826(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING event ROLEREVOKED185(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING function HASROLE367(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING return _roles[role].members.CONTAINS556(account); } function GETROLEMEMBERCOUNT938(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING return _roles[role].members.LENGTH118(); } function GETROLEMEMBER19(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING return _roles[role].members.AT34(index); } function GETROLEADMIN235(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING return _roles[role].adminRole; } function GRANTROLE137(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE367(_roles[role].adminRole, _MSGSENDER905()), "AccessControl: sender must be an admin to grant"); _GRANTROLE954(role, account); } function REVOKEROLE670(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE367(_roles[role].adminRole, _MSGSENDER905()), "AccessControl: sender must be an admin to revoke"); _REVOKEROLE460(role, account); } function RENOUNCEROLE777(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(account == _MSGSENDER905(), "AccessControl: can only renounce roles for self"); _REVOKEROLE460(role, account); } function _SETUPROLE461(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING _GRANTROLE954(role, account); } function _SETROLEADMIN512(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING emit ROLEADMINCHANGED88(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _GRANTROLE954(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.ADD236(account)) { emit ROLEGRANTED826(role, account, _MSGSENDER905()); } } function _REVOKEROLE460(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.REMOVE884(account)) { emit ROLEREVOKED185(role, account, _MSGSENDER905()); } } } // contract YDVRewardsDistributor is AccessControl, Ownable { using SafeERC20 for IERC20; using Address for address; IERC20 public rewardToken; address[] public ydvs; bytes32 public constant ydv_rewards665 = keccak256("YDV_REWARDS"); //inject NONSTANDARD NAMING constructor(address _rally) public { rewardToken = IERC20(_rally); _SETUPROLE461(default_admin_role567, msg.sender); } function TRANSFERREWARD486(uint256 _amount) external { //inject NONSTANDARD NAMING require (HASROLE367(ydv_rewards665, msg.sender), "only ydv rewards"); rewardToken.SAFETRANSFER115(msg.sender, _amount); } function ADDYDV918(address _ydv) external ONLYOWNER378 { //inject NONSTANDARD NAMING GRANTROLE137(ydv_rewards665, _ydv); ydvs.push(_ydv); } function YDVSLENGTH403() external view returns (uint256) { //inject NONSTANDARD NAMING return ydvs.length; } } // interface Vault { function BALANCEOF1000(address) external view returns (uint256); //inject NONSTANDARD NAMING function TOKEN783() external view returns (address); //inject NONSTANDARD NAMING function CLAIMINSURANCE535() external; //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE194() external view returns (uint256); //inject NONSTANDARD NAMING function DEPOSIT941(uint) external; //inject NONSTANDARD NAMING function WITHDRAW419(uint) external; //inject NONSTANDARD NAMING } // contract YDVErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, REJECTION } enum FailureInfo { SET_INDIVIDUAL_SOFT_CAP_CHECK, SET_GLOBAL_SOFT_CAP_CHECK } event FAILURE308(uint error, uint info, uint detail); //inject NONSTANDARD NAMING function FAIL273(Error err, FailureInfo info) internal returns (uint) { //inject NONSTANDARD NAMING emit FAILURE308(uint(err), uint(info), 0); return uint(err); } function FAILOPAQUE544(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { //inject NONSTANDARD NAMING emit FAILURE308(uint(err), uint(info), opaqueError); return uint(err); } } // contract RallyToken is ERC20 { //15 billion fixed token supply with default 18 decimals uint256 public constant token_supply159 = 15 * 10**9 * 10**18; //inject NONSTANDARD NAMING constructor ( address _escrow ) public ERC20( "Rally", "RLY" ) { _MINT985(_escrow, token_supply159); } } // contract NoMintLiquidityRewardPools is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of RLY // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRallyPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRallyPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. RLYs to distribute per block. uint256 lastRewardBlock; // Last block number that RLYs distribution occurs. uint256 accRallyPerShare; // Accumulated RLYs per share, times 1e12. See below. } // The RALLY TOKEN! RallyToken public rally; // RLY tokens created per block. uint256 public rallyPerBlock; // 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 block number when RLY mining starts. uint256 public startBlock; event DEPOSIT927(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW385(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW903(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING constructor( RallyToken _rally, uint256 _rallyPerBlock, uint256 _startBlock ) public { rally = _rally; rallyPerBlock = _rallyPerBlock; startBlock = _startBlock; } function POOLLENGTH610() external view returns (uint256) { //inject NONSTANDARD NAMING 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 ADD236(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public ONLYOWNER378 { //inject NONSTANDARD NAMING if (_withUpdate) { MASSUPDATEPOOLS681(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.ADD236(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRallyPerShare: 0 })); } // Update the given pool's RLY allocation point. Can only be called by the owner. function SET138(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public ONLYOWNER378 { //inject NONSTANDARD NAMING if (_withUpdate) { MASSUPDATEPOOLS681(); } totalAllocPoint = totalAllocPoint.SUB786(poolInfo[_pid].allocPoint).ADD236(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // update the rate at which RLY is allocated to rewards, can only be called by the owner function SETRALLYPERBLOCK200(uint256 _rallyPerBlock) public ONLYOWNER378 { //inject NONSTANDARD NAMING MASSUPDATEPOOLS681(); rallyPerBlock = _rallyPerBlock; } // View function to see pending RLYs on frontend. function PENDINGRALLY232(uint256 _pid, address _user) external view returns (uint256) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRallyPerShare = pool.accRallyPerShare; uint256 lpSupply = pool.lpToken.BALANCEOF1000(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = block.number.SUB786(pool.lastRewardBlock); uint256 rallyReward = multiplier.MUL747(rallyPerBlock).MUL747(pool.allocPoint).DIV140(totalAllocPoint); accRallyPerShare = accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(lpSupply)); } return user.amount.MUL747(accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS681() public { //inject NONSTANDARD NAMING uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { UPDATEPOOL112(pid); } } // Update reward variables of the given pool to be up-to-date. // No new RLY are minted, distribution is dependent on sufficient RLY tokens being sent to this contract function UPDATEPOOL112(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.BALANCEOF1000(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = block.number.SUB786(pool.lastRewardBlock); uint256 rallyReward = multiplier.MUL747(rallyPerBlock).MUL747(pool.allocPoint).DIV140(totalAllocPoint); pool.accRallyPerShare = pool.accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to pool for RLY allocation. function DEPOSIT941(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; UPDATEPOOL112(_pid); if (user.amount > 0) { uint256 pending = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt); if(pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.SAFETRANSFERFROM287(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD236(_amount); } user.rewardDebt = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12); emit DEPOSIT927(msg.sender, _pid, _amount); } // Withdraw LP tokens from pool. function WITHDRAW419(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); UPDATEPOOL112(_pid); uint256 pending = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt); if(pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.SUB786(_amount); pool.lpToken.SAFETRANSFER115(address(msg.sender), _amount); } user.rewardDebt = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12); emit WITHDRAW385(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function EMERGENCYWITHDRAW757(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.SAFETRANSFER115(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW903(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe RLY transfer function, just in case pool does not have enough RLY; either rounding error or we're not supplying more rewards function SAFERALLYTRANSFER520(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING uint256 rallyBal = rally.BALANCEOF1000(address(this)); if (_amount > rallyBal) { rally.TRANSFER912(_to, rallyBal); } else { rally.TRANSFER912(_to, _amount); } } } // contract YieldDelegatingVaultStorage2 { address public vault; YDVRewardsDistributor rewards; IERC20 public rally; address public treasury; IERC20 public token; uint256 public delegatePercent; mapping(address => uint256) public rewardDebt; uint256 public totalDeposits; uint256 public rewardPerToken; uint256 public accRallyPerShare; bool public lrEnabled; uint256 public pid; NoMintLiquidityRewardPools lrPools; } // contract YieldDelegatingVault2 is ERC20, YieldDelegatingVaultStorage2, YieldDelegatingVaultEvent2, Ownable, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; constructor ( address _vault, address _rewards, address _treasury, uint256 _delegatePercent, uint256 _rewardPerToken ) public ERC20( string(abi.encodePacked("rally delegating ", ERC20(Vault(_vault).TOKEN783()).NAME654())), string(abi.encodePacked("rd", ERC20(Vault(_vault).TOKEN783()).SYMBOL381())) ) { _SETUPDECIMALS502(ERC20(Vault(_vault).TOKEN783()).DECIMALS442()); token = IERC20(Vault(_vault).TOKEN783()); //token being deposited in the referenced vault vault = _vault; //address of the vault we're proxying rewards = YDVRewardsDistributor(_rewards); rally = rewards.rewardToken(); treasury = _treasury; delegatePercent = _delegatePercent; rewardPerToken = _rewardPerToken; totalDeposits = 0; accRallyPerShare = 0; lrEnabled = false; } function SETTREASURY672(address newTreasury) public ONLYOWNER378 { //inject NONSTANDARD NAMING require(newTreasury != address(0), "treasure should be valid address"); address oldTreasury = treasury; treasury = newTreasury; emit NEWTREASURY741(oldTreasury, newTreasury); } function SETNEWREWARDPERTOKEN724(uint256 newRewardPerToken) public ONLYOWNER378 { //inject NONSTANDARD NAMING uint256 oldRewardPerToken = rewardPerToken; rewardPerToken = newRewardPerToken; emit NEWREWARDPERTOKEN257(oldRewardPerToken, newRewardPerToken); } function EARNED974(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEFORREWARDSCALC156(account).MUL747(accRallyPerShare).DIV140(1e12).SUB786(rewardDebt[account]); } function BALANCE265() public view returns (uint256) { //inject NONSTANDARD NAMING return (IERC20(vault)).BALANCEOF1000(address(this)); //how many shares do we have in the vault we are delegating to } //for the purpose of rewards calculations, a user's balance is the total of what's in their wallet //and what they have deposited in the rewards pool (if it's active). //transfer restriction ensures accuracy of this sum function BALANCEFORREWARDSCALC156(address account) internal view returns (uint256) { //inject NONSTANDARD NAMING if (lrEnabled) { (uint256 amount, ) = lrPools.userInfo(pid, account); return BALANCEOF1000(account).ADD236(amount); } return BALANCEOF1000(account); } function DEPOSITALL490() external { //inject NONSTANDARD NAMING DEPOSIT941(token.BALANCEOF1000(msg.sender)); } function DEPOSIT941(uint256 _amount) public NONREENTRANT44 { //inject NONSTANDARD NAMING uint256 pending = EARNED974(msg.sender); if (pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } uint256 _pool = BALANCE265(); uint256 _before = token.BALANCEOF1000(address(this)); token.SAFETRANSFERFROM287(msg.sender, address(this), _amount); uint256 _after = token.BALANCEOF1000(address(this)); _amount = _after.SUB786(_before); totalDeposits = totalDeposits.ADD236(_amount); token.APPROVE378(vault, _amount); Vault(vault).DEPOSIT941(_amount); uint256 _after_pool = BALANCE265(); uint256 _new_shares = _after_pool.SUB786(_pool); //new vault tokens representing my added vault shares //translate vault shares into delegating vault shares uint256 shares = 0; if (TOTALSUPPLY709() == 0) { shares = _new_shares; } else { shares = (_new_shares.MUL747(TOTALSUPPLY709())).DIV140(_pool); } _MINT985(msg.sender, shares); rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12); } function DEPOSITYTOKEN556(uint256 _yamount) public NONREENTRANT44 { //inject NONSTANDARD NAMING uint256 pending = EARNED974(msg.sender); if (pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } uint256 _before = IERC20(vault).BALANCEOF1000(address(this)); IERC20(vault).SAFETRANSFERFROM287(msg.sender, address(this), _yamount); uint256 _after = IERC20(vault).BALANCEOF1000(address(this)); _yamount = _after.SUB786(_before); uint _underlyingAmount = _yamount.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18); totalDeposits = totalDeposits.ADD236(_underlyingAmount); //translate vault shares into delegating vault shares uint256 shares = 0; if (TOTALSUPPLY709() == 0) { shares = _yamount; } else { shares = (_yamount.MUL747(TOTALSUPPLY709())).DIV140(_before); } _MINT985(msg.sender, shares); rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12); } function WITHDRAWALL908() external { //inject NONSTANDARD NAMING WITHDRAW419(BALANCEOF1000(msg.sender)); } function WITHDRAW419(uint256 _shares) public NONREENTRANT44 { //inject NONSTANDARD NAMING uint256 pending = EARNED974(msg.sender); if (pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } uint256 r = (BALANCE265().MUL747(_shares)).DIV140(TOTALSUPPLY709()); _BURN126(msg.sender, _shares); SAFEREDUCETOTALDEPOSITS144(r.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18)); rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12); uint256 _before = token.BALANCEOF1000(address(this)); Vault(vault).WITHDRAW419(r); uint256 _after = token.BALANCEOF1000(address(this)); uint256 toTransfer = _after.SUB786(_before); token.SAFETRANSFER115(msg.sender, toTransfer); } //in case of rounding errors converting between vault tokens and underlying value function SAFEREDUCETOTALDEPOSITS144(uint256 _amount) internal { //inject NONSTANDARD NAMING if (_amount > totalDeposits) { totalDeposits = 0; } else { totalDeposits = totalDeposits.SUB786(_amount); } } function WITHDRAWYTOKEN466(uint256 _shares) public NONREENTRANT44 { //inject NONSTANDARD NAMING uint256 pending = EARNED974(msg.sender); if (pending > 0) { SAFERALLYTRANSFER520(msg.sender, pending); } uint256 r = (BALANCE265().MUL747(_shares)).DIV140(TOTALSUPPLY709()); _BURN126(msg.sender, _shares); rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12); uint256 _amount = r.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18); SAFEREDUCETOTALDEPOSITS144(_amount); IERC20(vault).SAFETRANSFER115(msg.sender, r); } // Safe RLY transfer function, just in case pool does not have enough RLY due to rounding error function SAFERALLYTRANSFER520(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING uint256 rallyBal = rally.BALANCEOF1000(address(this)); if (_amount > rallyBal) { rally.TRANSFER912(_to, rallyBal); } else { rally.TRANSFER912(_to, _amount); } } //how much are our shares of the underlying vault worth relative to the deposit value? returns value denominated in vault tokens function AVAILABLEYIELD882() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 totalValue = BALANCE265().MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18); if (totalValue > totalDeposits) { uint256 earnings = totalValue.SUB786(totalDeposits); return earnings.MUL747(1e18).DIV140(Vault(vault).GETPRICEPERFULLSHARE194()); } return 0; } //transfer accumulated yield to treasury, update totalDeposits to ensure availableYield following //harvest is 0, and increase accumulated rally rewards //harvest fails if we're unable to fund rewards function HARVEST82() public ONLYOWNER378 { //inject NONSTANDARD NAMING uint256 _availableYield = AVAILABLEYIELD882(); if (_availableYield > 0) { uint256 rallyReward = _availableYield.MUL747(delegatePercent).DIV140(10000).MUL747(rewardPerToken).DIV140(1e18); rewards.TRANSFERREWARD486(rallyReward); IERC20(vault).SAFETRANSFER115(treasury, _availableYield.MUL747(delegatePercent).DIV140(10000)); accRallyPerShare = accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(TOTALSUPPLY709())); totalDeposits = BALANCE265().MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18); } } //one way ticket and only callable once function ENABLELIQUIDITYREWARDS505(address _lrPools, uint256 _pid) public ONLYOWNER378 { //inject NONSTANDARD NAMING (IERC20 lpToken,,,) = NoMintLiquidityRewardPools(_lrPools).poolInfo(_pid); require(address(lpToken) == address(this), "invalid liquidity rewards setup"); require(lrEnabled == false, "liquidity rewards already enabled"); lrEnabled = true; lrPools = NoMintLiquidityRewardPools(_lrPools); pid = _pid; } //override underlying _transfer implementation; YDV shares can only be transferred to/from the liquidity rewards pool function _TRANSFER205(address sender, address recipient, uint256 amount) internal override { //inject NONSTANDARD NAMING require(lrEnabled, "transfer rejected"); require(sender == address(lrPools) || recipient == address(lrPools), "transfer rejected"); super._TRANSFER205(sender, recipient, amount); } }
inject NONSTANDARD NAMING
function TOTALSUPPLY709() public view override returns (uint256) {
12,852,107
pragma solidity ^0.6.0; interface CHIInterface { function mint(uint256 value) external; function free(uint256 value) external returns (uint256); function balanceOf(address) external view returns (uint); function approve(address, uint256) external; } contract ChiHelpers { /** * @dev CHI token Address */ function getCHIAddress() internal pure returns (address) { return 0x0000000000004946c0e9F43F4Dee607b0eF1fA1c; } /** * @dev Connector Details. */ function connectorID() public view returns(uint model, uint id) { (model, id) = (1, 36); } } contract ChiResolver is ChiHelpers { /** * @dev Mint CHI token. * @param amt token amount to mint. */ function mint(uint amt) public payable { uint _amt = amt == uint(-1) ? 140 : amt; require(_amt <= 140, "Max minting is 140 chi"); CHIInterface(getCHIAddress()).mint(_amt); } /** * @dev burn CHI token. * @param amt token amount to burn. */ function burn(uint amt) public payable { CHIInterface chiToken = CHIInterface(getCHIAddress()); uint _amt = amt == uint(-1) ? chiToken.balanceOf(address(this)) : amt; chiToken.approve(address(chiToken), _amt); chiToken.free(_amt); } } contract ConnectCHI is ChiResolver { string public name = "CHI-v1"; }
CHI token Address/
function getCHIAddress() internal pure returns (address) { return 0x0000000000004946c0e9F43F4Dee607b0eF1fA1c; }
576,658
./partial_match/1/0x0176A80CcCA7514eD1C32ba1866b8EC497bbF040/sources/StoryOfShiba.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Story Of Shiba", "SOS") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 2; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 1; uint256 totalSupply = 100000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(address(marketingWallet), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(address(marketingWallet), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
2,740,860
./partial_match/1/0xc40CdBf22a74757819769cA2208E3fB2C7aEC5de/sources/CompliantCrowdsale.sol
approve buy tokens request nonce request recorded at this particular nonce/
function approveMint(uint256 nonce) external onlyValidator { require(_approveMint(nonce)); }
3,699,407
./full_match/5/0x3655A0FfF28034894A5750168e0069a2f6d8aE43/sources/contracts/333Updated.sol
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 memory _data ) public payable virtual override { transferFrom(from, to, tokenId); if (to.code.length != 0) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } }
1,850,717
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "../governance/Managed.sol"; import "../upgrades/GraphUpgradeable.sol"; import "./DisputeManagerStorage.sol"; import "./IDisputeManager.sol"; /* * @title DisputeManager * @dev Provides a way to align the incentives of participants by having slashing as deterrent * for incorrect behaviour. * * There are two types of disputes that can be created: Query disputes and Indexing disputes. * * Query Disputes: * Graph nodes receive queries and return responses with signed receipts called attestations. * An attestation can be disputed if the consumer thinks the query response was invalid. * Indexers use the derived private key for an allocation to sign attestations. * * Indexing Disputes: * Indexers present a Proof of Indexing (POI) when they close allocations to prove * they were indexing a subgraph. The Staking contract emits that proof with the format * keccak256(indexer.address, POI). * Any challenger can dispute the validity of a POI by submitting a dispute to this contract * along with a deposit. * * Arbitration: * Disputes can only be accepted, rejected or drawn by the arbitrator role that can be delegated * to a EOA or DAO. */ contract DisputeManager is DisputeManagerV1Storage, GraphUpgradeable, IDisputeManager { using SafeMath for uint256; // -- EIP-712 -- bytes32 private constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Protocol"); bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0"); bytes32 private constant DOMAIN_SALT = 0xa070ffb1cd7409649bf77822cce74495468e06dbfaef09556838bf188679b9c2; bytes32 private constant RECEIPT_TYPE_HASH = keccak256( "Receipt(bytes32 requestCID,bytes32 responseCID,bytes32 subgraphDeploymentID)" ); // -- Constants -- uint256 private constant ATTESTATION_SIZE_BYTES = 161; uint256 private constant RECEIPT_SIZE_BYTES = 96; uint256 private constant SIG_R_LENGTH = 32; uint256 private constant SIG_S_LENGTH = 32; uint256 private constant SIG_R_OFFSET = RECEIPT_SIZE_BYTES; uint256 private constant SIG_S_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH; uint256 private constant SIG_V_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH + SIG_S_LENGTH; uint256 private constant UINT8_BYTE_LENGTH = 1; uint256 private constant BYTES32_BYTE_LENGTH = 32; uint256 private constant MAX_PPM = 1000000; // 100% in parts per million // -- Events -- /** * @dev Emitted when a query dispute is created for `subgraphDeploymentID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman and `attestation` submitted. */ event QueryDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, bytes32 subgraphDeploymentID, bytes attestation ); /** * @dev Emitted when an indexing dispute is created for `allocationID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman. */ event IndexingDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, address allocationID ); /** * @dev Emitted when arbitrator accepts a `disputeID` to `indexer` created by `fisherman`. * The event emits the amount `tokens` transferred to the fisherman, the deposit plus reward. */ event DisputeAccepted( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator rejects a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` burned from the fisherman deposit. */ event DisputeRejected( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator draw a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` used as deposit and returned to the fisherman. */ event DisputeDrawn( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when two disputes are in conflict to link them. * This event will be emitted after each DisputeCreated event is emitted * for each of the individual disputes. */ event DisputeLinked(bytes32 indexed disputeID1, bytes32 indexed disputeID2); /** * @dev Check if the caller is the arbitrator. */ modifier onlyArbitrator { require(msg.sender == arbitrator, "Caller is not the Arbitrator"); _; } /** * @dev Initialize this contract. * @param _arbitrator Arbitrator role * @param _minimumDeposit Minimum deposit required to create a Dispute * @param _fishermanRewardPercentage Percent of slashed funds for fisherman (ppm) * @param _slashingPercentage Percentage of indexer stake slashed (ppm) */ function initialize( address _controller, address _arbitrator, uint256 _minimumDeposit, uint32 _fishermanRewardPercentage, uint32 _slashingPercentage ) external onlyImpl { Managed._initialize(_controller); // Settings _setArbitrator(_arbitrator); _setMinimumDeposit(_minimumDeposit); _setFishermanRewardPercentage(_fishermanRewardPercentage); _setSlashingPercentage(_slashingPercentage); // EIP-712 domain separator DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) ); } /** * @dev Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function setArbitrator(address _arbitrator) external override onlyGovernor { _setArbitrator(_arbitrator); } /** * @dev Internal: Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function _setArbitrator(address _arbitrator) private { require(_arbitrator != address(0), "Arbitrator must be set"); arbitrator = _arbitrator; emit ParameterUpdated("arbitrator"); } /** * @dev Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function setMinimumDeposit(uint256 _minimumDeposit) external override onlyGovernor { _setMinimumDeposit(_minimumDeposit); } /** * @dev Internal: Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function _setMinimumDeposit(uint256 _minimumDeposit) private { require(_minimumDeposit > 0, "Minimum deposit must be set"); minimumDeposit = _minimumDeposit; emit ParameterUpdated("minimumDeposit"); } /** * @dev Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function setFishermanRewardPercentage(uint32 _percentage) external override onlyGovernor { _setFishermanRewardPercentage(_percentage); } /** * @dev Internal: Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function _setFishermanRewardPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Reward percentage must be below or equal to MAX_PPM"); fishermanRewardPercentage = _percentage; emit ParameterUpdated("fishermanRewardPercentage"); } /** * @dev Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function setSlashingPercentage(uint32 _percentage) external override onlyGovernor { _setSlashingPercentage(_percentage); } /** * @dev Internal: Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function _setSlashingPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Slashing percentage must be below or equal to MAX_PPM"); slashingPercentage = _percentage; emit ParameterUpdated("slashingPercentage"); } /** * @dev Return whether a dispute exists or not. * @notice Return if dispute with ID `_disputeID` exists * @param _disputeID True if dispute already exists */ function isDisputeCreated(bytes32 _disputeID) public override view returns (bool) { return disputes[_disputeID].fisherman != address(0); } /** * @dev Get the message hash that an indexer used to sign the receipt. * Encodes a receipt using a domain separator, as described on * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification. * @notice Return the message hash used to sign the receipt * @param _receipt Receipt returned by indexer and submitted by fisherman * @return Message hash used to sign the receipt */ function encodeHashReceipt(Receipt memory _receipt) public override view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", // EIP-191 encoding pad, EIP-712 version 1 DOMAIN_SEPARATOR, keccak256( abi.encode( RECEIPT_TYPE_HASH, _receipt.requestCID, _receipt.responseCID, _receipt.subgraphDeploymentID ) // EIP 712-encoded message hash ) ) ); } /** * @dev Returns if two attestations are conflicting. * Everything must match except for the responseID. * @param _attestation1 Attestation * @param _attestation2 Attestation * @return True if the two attestations are conflicting */ function areConflictingAttestations( Attestation memory _attestation1, Attestation memory _attestation2 ) public override pure returns (bool) { return (_attestation1.requestCID == _attestation2.requestCID && _attestation1.subgraphDeploymentID == _attestation2.subgraphDeploymentID && _attestation1.responseCID != _attestation2.responseCID); } /** * @dev Returns the indexer that signed an attestation. * @param _attestation Attestation * @return Indexer address */ function getAttestationIndexer(Attestation memory _attestation) public override view returns (address) { // Get attestation signer, allocationID address allocationID = _recoverAttestationSigner(_attestation); IStaking.Allocation memory alloc = staking().getAllocation(allocationID); require(alloc.indexer != address(0), "Indexer cannot be found for the attestation"); require( alloc.subgraphDeploymentID == _attestation.subgraphDeploymentID, "Allocation and attestation subgraphDeploymentID must match" ); return alloc.indexer; } /** * @dev Get the fisherman reward for a given indexer stake. * @notice Return the fisherman reward based on the `_indexer` stake * @param _indexer Indexer to be slashed * @return Reward calculated as percentage of the indexer slashed funds */ function getTokensToReward(address _indexer) public override view returns (uint256) { uint256 tokens = getTokensToSlash(_indexer); if (tokens == 0) { return 0; } return uint256(fishermanRewardPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Get the amount of tokens to slash for an indexer based on the current stake. * @param _indexer Address of the indexer * @return Amount of tokens to slash */ function getTokensToSlash(address _indexer) public override view returns (uint256) { uint256 tokens = staking().getIndexerStakedTokens(_indexer); // slashable tokens if (tokens == 0) { return 0; } return uint256(slashingPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Create a query dispute for the arbitrator to resolve. * This function is called by a fisherman that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _attestationData Attestation bytes submitted by the fisherman * @param _deposit Amount of tokens staked as deposit */ function createQueryDispute(bytes calldata _attestationData, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createQueryDisputeWithAttestation( msg.sender, _deposit, _parseAttestation(_attestationData), _attestationData ); } /** * @dev Create query disputes for two conflicting attestations. * A conflicting attestation is a proof presented by two different indexers * where for the same request on a subgraph the response is different. * For this type of dispute the submitter is not required to present a deposit * as one of the attestation is considered to be right. * Two linked disputes will be created and if the arbitrator resolve one, the other * one will be automatically resolved. * @param _attestationData1 First attestation data submitted * @param _attestationData2 Second attestation data submitted * @return DisputeID1, DisputeID2 */ function createQueryDisputeConflict( bytes calldata _attestationData1, bytes calldata _attestationData2 ) external override returns (bytes32, bytes32) { address fisherman = msg.sender; // Parse each attestation Attestation memory attestation1 = _parseAttestation(_attestationData1); Attestation memory attestation2 = _parseAttestation(_attestationData2); // Test that attestations are conflicting require( areConflictingAttestations(attestation1, attestation2), "Attestations must be in conflict" ); // Create the disputes // The deposit is zero for conflicting attestations bytes32 dID1 = _createQueryDisputeWithAttestation( fisherman, 0, attestation1, _attestationData1 ); bytes32 dID2 = _createQueryDisputeWithAttestation( fisherman, 0, attestation2, _attestationData2 ); // Store the linked disputes to be resolved disputes[dID1].relatedDisputeID = dID2; disputes[dID2].relatedDisputeID = dID1; // Emit event that links the two created disputes emit DisputeLinked(dID1, dID2); return (dID1, dID2); } /** * @dev Create a query dispute passing the parsed attestation. * To be used in createQueryDispute() and createQueryDisputeConflict() * to avoid calling parseAttestation() multiple times * `_attestationData` is only passed to be emitted * @param _fisherman Creator of dispute * @param _deposit Amount of tokens staked as deposit * @param _attestation Attestation struct parsed from bytes * @param _attestationData Attestation bytes submitted by the fisherman * @return DisputeID */ function _createQueryDisputeWithAttestation( address _fisherman, uint256 _deposit, Attestation memory _attestation, bytes memory _attestationData ) private returns (bytes32) { // Get the indexer that signed the attestation address indexer = getAttestationIndexer(_attestation); // The indexer is disputable require(staking().hasStake(indexer), "Dispute indexer has no stake"); // Create a disputeID bytes32 disputeID = keccak256( abi.encodePacked( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID, indexer, _fisherman ) ); // Only one dispute for a (indexer, subgraphDeploymentID) at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Store dispute disputes[disputeID] = Dispute( indexer, _fisherman, _deposit, 0 // no related dispute ); emit QueryDisputeCreated( disputeID, indexer, _fisherman, _deposit, _attestation.subgraphDeploymentID, _attestationData ); return disputeID; } /** * @dev Create an indexing dispute for the arbitrator to resolve. * The disputes are created in reference to an allocationID * This function is called by a challenger that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _allocationID The allocation to dispute * @param _deposit Amount of tokens staked as deposit */ function createIndexingDispute(address _allocationID, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createIndexingDisputeWithAllocation(msg.sender, _deposit, _allocationID); } /** * @dev Create indexing dispute internal function. * @param _fisherman The challenger creating the dispute * @param _deposit Amount of tokens staked as deposit * @param _allocationID Allocation disputed */ function _createIndexingDisputeWithAllocation( address _fisherman, uint256 _deposit, address _allocationID ) private returns (bytes32) { // Create a disputeID bytes32 disputeID = keccak256(abi.encodePacked(_allocationID)); // Only one dispute for an allocationID at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Allocation must exist IStaking.Allocation memory alloc = staking().getAllocation(_allocationID); require(alloc.indexer != address(0), "Dispute allocation must exist"); // The indexer must be disputable require(staking().hasStake(alloc.indexer), "Dispute indexer has no stake"); // Store dispute disputes[disputeID] = Dispute(alloc.indexer, _fisherman, _deposit, 0); emit IndexingDisputeCreated(disputeID, alloc.indexer, _fisherman, _deposit, _allocationID); return disputeID; } /** * @dev The arbitrator accepts a dispute as being valid. * @notice Accept a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be accepted */ function acceptDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Slash uint256 tokensToReward = _slashIndexer(dispute.indexer, dispute.fisherman); // Give the fisherman their deposit back if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeAccepted( _disputeID, dispute.indexer, dispute.fisherman, dispute.deposit.add(tokensToReward) ); } /** * @dev The arbitrator rejects a dispute as being invalid. * @notice Reject a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be rejected */ function rejectDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Handle conflicting dispute if any require( !_isDisputeInConflict(dispute), "Dispute for conflicting attestation, must accept the related ID to reject" ); // Burn the fisherman's deposit if (dispute.deposit > 0) { graphToken().burn(dispute.deposit); } emit DisputeRejected(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev The arbitrator draws dispute. * @notice Ignore a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be disregarded */ function drawDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Return deposit to the fisherman if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeDrawn(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev Resolve a dispute by removing it from storage and returning a memory copy. * @param _disputeID ID of the dispute to resolve * @return Dispute */ function _resolveDispute(bytes32 _disputeID) private returns (Dispute memory) { require(isDisputeCreated(_disputeID), "Dispute does not exist"); Dispute memory dispute = disputes[_disputeID]; // Resolve dispute delete disputes[_disputeID]; // Re-entrancy return dispute; } /** * @dev Returns whether the dispute is for a conflicting attestation or not. * @param _dispute Dispute * @return True conflicting attestation dispute */ function _isDisputeInConflict(Dispute memory _dispute) private pure returns (bool) { return _dispute.relatedDisputeID != 0; } /** * @dev Resolve the conflicting dispute if there is any for the one passed to this function. * @param _dispute Dispute * @return True if resolved */ function _resolveDisputeInConflict(Dispute memory _dispute) private returns (bool) { if (_isDisputeInConflict(_dispute)) { bytes32 relatedDisputeID = _dispute.relatedDisputeID; delete disputes[relatedDisputeID]; return true; } return false; } /** * @dev Pull deposit from submitter account. * @param _deposit Amount of tokens to deposit */ function _pullSubmitterDeposit(uint256 _deposit) private { // Ensure that fisherman has staked at least the minimum amount require(_deposit >= minimumDeposit, "Dispute deposit is under minimum required"); // Transfer tokens to deposit from fisherman to this contract require( graphToken().transferFrom(msg.sender, address(this), _deposit), "Cannot transfer tokens to deposit" ); } /** * @dev Make the staking contract slash the indexer and reward the challenger. * Give the challenger a reward equal to the fishermanRewardPercentage of slashed amount * @param _indexer Address of the indexer * @param _challenger Address of the challenger * @return Dispute reward tokens */ function _slashIndexer(address _indexer, address _challenger) private returns (uint256) { // Have staking contract slash the indexer and reward the fisherman // Give the fisherman a reward equal to the fishermanRewardPercentage of slashed amount uint256 tokensToSlash = getTokensToSlash(_indexer); uint256 tokensToReward = getTokensToReward(_indexer); require(tokensToSlash > 0, "Dispute has zero tokens to slash"); staking().slash(_indexer, tokensToSlash, tokensToReward, _challenger); return tokensToReward; } /** * @dev Recover the signer address of the `_attestation`. * @param _attestation The attestation struct * @return Signer address */ function _recoverAttestationSigner(Attestation memory _attestation) private view returns (address) { // Obtain the hash of the fully-encoded message, per EIP-712 encoding Receipt memory receipt = Receipt( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID ); bytes32 messageHash = encodeHashReceipt(receipt); // Obtain the signer of the fully-encoded EIP-712 message hash // NOTE: The signer of the attestation is the indexer that served the request return ECDSA.recover( messageHash, abi.encodePacked(_attestation.r, _attestation.s, _attestation.v) ); } /** * @dev Get the running network chain ID * @return The chain ID */ function _getChainID() private pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Parse the bytes attestation into a struct from `_data`. * @return Attestation struct */ function _parseAttestation(bytes memory _data) private pure returns (Attestation memory) { // Check attestation data length require(_data.length == ATTESTATION_SIZE_BYTES, "Attestation must be 161 bytes long"); // Decode receipt (bytes32 requestCID, bytes32 responseCID, bytes32 subgraphDeploymentID) = abi.decode( _data, (bytes32, bytes32, bytes32) ); // Decode signature // Signature is expected to be in the order defined in the Attestation struct bytes32 r = _toBytes32(_data, SIG_R_OFFSET); bytes32 s = _toBytes32(_data, SIG_S_OFFSET); uint8 v = _toUint8(_data, SIG_V_OFFSET); return Attestation(requestCID, responseCID, subgraphDeploymentID, r, s, v); } /** * @dev Parse a uint8 from `_bytes` starting at offset `_start`. * @return uint8 value */ function _toUint8(bytes memory _bytes, uint256 _start) private pure returns (uint8) { require(_bytes.length >= (_start + UINT8_BYTE_LENGTH), "Bytes: out of bounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } /** * @dev Parse a bytes32 from `_bytes` starting at offset `_start`. * @return bytes32 value */ function _toBytes32(bytes memory _bytes, uint256 _start) private pure returns (bytes32) { require(_bytes.length >= (_start + BYTES32_BYTE_LENGTH), "Bytes: out of bounds"); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } }
The arbitrator rejects a dispute as being invalid. Reject a dispute with ID `_disputeID` _disputeID ID of the dispute to be rejected/ Handle conflicting dispute if any Burn the fisherman's deposit
function rejectDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); require( !_isDisputeInConflict(dispute), "Dispute for conflicting attestation, must accept the related ID to reject" ); if (dispute.deposit > 0) { graphToken().burn(dispute.deposit); } emit DisputeRejected(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); }
908,970
./full_match/4/0xD10fEd0e71Cfd4728b48eC7bdea0bEDD6075Cb78/sources/sellSwap.sol
/ value = orderIdValue[bytes16(keccak256(abi.encodePacked(seller, chainIdAdapterIdAssetIdPrice, foreignAddress)))];
function getOrderValue(address seller, bytes32 chainIdAdapterIdAssetIdPrice, bytes32 foreignAddress) view external returns (uint256 value) { }
12,460,095
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; /* f_1 - 274287 - 99825 - 48525 f_2 - 148063 - 103637 - 52337 f_3 - 274959 - 99835 - 48535 */ // uint8 storage and setter contract Library_1 { address[] owners; mapping(address=>uint256) ownerBalances; function SplitFunds() public payable { distributeFunds(msg.value); } function addOwner() public { // this should have checks, using this to just illustrate a point owners.push(msg.sender); } function distributeFunds(uint256 amount) private { uint256 split = amount / owners.length; uint256 remainder = amount % owners.length; ownerBalances[owners[0]] += remainder; for(uint i=0; i < owners.length;i++) { ownerBalances[owners[i]] += split; } } } contract Library_2 { address[] owners; mapping(address=>uint256) ownerBalances; function SplitFunds() public payable { FeeSplitter.distributeFunds(msg.value, owners, ownerBalances); } function addOwner() public { // this should have checks, using this to just illustrate a point owners.push(msg.sender); } } contract Library_3 { address[] owners; mapping(address=>uint256) ownerBalances; function SplitFunds() public payable { distributeFunds(msg.value, owners, ownerBalances); } function addOwner() public { // this should have checks, using this to just illustrate a point owners.push(msg.sender); } function distributeFunds(uint256 amount, address[] storage owners, mapping(address => uint256) storage ownerBalances) private { uint256 split = amount / owners.length; uint256 remainder = amount % owners.length; ownerBalances[owners[0]] += remainder; for(uint i=0; i < owners.length;i++) { ownerBalances[owners[i]] += split; } } } library FeeSplitter{ function distributeFunds(uint256 amount, address[] storage owners, mapping(address => uint256) storage ownerBalances) public { uint256 split = amount / owners.length; uint256 remainder = amount % owners.length; ownerBalances[owners[0]] += remainder; for(uint i=0; i < owners.length;i++) { ownerBalances[owners[i]] += split; } } }
this should have checks, using this to just illustrate a point
function addOwner() public { owners.push(msg.sender); }
15,844,579
./full_match/97/0xce50445Fade594dd26312Ef3980cE0D1415950c8/sources/contracts/malamaca.sol
approve token transfer to cover all possible scenarios add the liquidity
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, marketingWallet, block.timestamp ); }
5,041,057
./full_match/43114/0x14cb5e12624E59346723924316410829B6f5Bb19/sources/thenamasterchef.sol
View function to see pending THENA on frontend.
function pendingThena(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accThenaPerShare = pool.accThenaPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 thenaReward = multiplier.mul(thenaPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accThenaPerShare = accThenaPerShare.add(thenaReward.mul(1e18).div(lpSupply)); } return user.amount.mul(accThenaPerShare).div(1e18).sub(user.rewardDebt); }
4,504,301
./full_match/137/0xf39dD76825dc5e4599832514B5a451F25B80828D/sources/contracts/MainV2Beta.sol
amountIn should be in terms of the token from which we are swapping
function swapExactInputSingle( address _returnBaseToken, address _tokenIn, uint256 _amountIn ) internal returns (uint256 amountOut) { uint256 amountOutMin = getAmountOutMin( _tokenIn, _returnBaseToken, _amountIn ); ISwapRouter.ExactInputSingleParams memory params = ISwapRouter .ExactInputSingleParams({ tokenIn: _tokenIn, tokenOut: _returnBaseToken, fee: poolFee, recipient: address(this), deadline: block.timestamp + 60, amountIn: _amountIn, amountOutMinimum: amountOutMin, sqrtPriceLimitX96: 0 }); amountOut = swapRouter.exactInputSingle(params); return amountOut; }
3,766,895
./partial_match/1/0x8b90bF500ef68C98B33f5CbE82821fC75c60534b/sources/src/Senator.sol
Consumes a nonce. Returns the current value and increments nonce./ For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be decremented or reset. This guarantees that the nonce never overflows. It is important to do x++ and not ++x here.
function _useNonce(address owner) internal virtual returns (uint256) { unchecked { return _nonces[owner]++; } }
9,245,221
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "hardhat/console.sol"; enum FeeExemption { NO_EXEMPTIONS, SENDER_EXEMPT, SENDER_AND_RECEIVER_EXEMPT, REDEEM_EXEMPT_AND_SENDER_EXEMPT, REDEEM_EXEMPT_AND_SENDER_AND_RECEIVER_EXEMPT, RECEIVER_EXEMPT, REDEEM_EXEMPT_AND_RECEIVER_EXEMPT, REDEEM_EXEMPT_ONLY } // File contracts/facades/IERC20.sol // Se-Identifier: MIT /** * @dev Interface of the ERC20 standard as defined in the EIP but with a burn friendly extra param added to transfer */ interface IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); /** * @dev 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, uint128 value, uint128 burnt); /** * @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/PyroToken.sol // Se-Identifier: MIT // import "hardhat/console.sol"; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract ERC20 is Context, IERC20 { mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _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-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 Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual; /** @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"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, uint128(amount), 0); } /** * @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"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), uint128(amount), 0); } /** * @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 Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // : MIT // File contracts/BurnableToken.sol //: Unlicense interface LiquidiyReceiverLike { function drain(address baseToken) external returns (uint256); } abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } contract PyroToken is ERC20, ReentrancyGuard { struct Configuration { address liquidityReceiver; IERC20 baseToken; address loanOfficer; bool pullPendingFeeRevenue; } struct DebtObligation { uint256 base; uint256 pyro; uint256 redeemRate; } Configuration public config; uint256 private constant ONE = 1 ether; /* Exemptions aren't a form of cronyism. Rather, it will be decided on fair, open cryptoeconomic rules to allow protocols that need to frequently work with pyroTokens to be able to do so without incurring untenable cost to themselves. Always bear in mind that the big AMMs including Behodler will burn PyroTokens with abandon and without exception. We don't need every single protocol to bear the cost of Pyro growth and would prefer to hit the high volume bots where they benefit most. Regarding fair cryptoeconomic incentives, a contract that requires burning a certain level of EYE would be a good example though we may get more sophisticated than that. As a pertinent example, since Behodler burns as a primitive, if we list a pyroToken for trade as burnable, then the total fee will be the Behodler burn fee plus the incoming transfer burn as well as the outgoing transfer burn when it is bought. This might be a little too much burning. In this case, we can turn of the transfer burns and still get the pyroToken burning on sale. */ mapping(address => FeeExemption) feeExemptionStatus; //By separating logic (loan officer) from state(debtObligations), we can upgrade the loan system without requiring existing borrowers migrate. //Seamless upgrade. This allows for better loan logic to replace the initial version. //By mapping debt on an individual pyroToken basis, it means each pyroToken can have it's own loan system. Potentially creating //a flourising of competing ideas. Seasteading for debt. mapping(address => DebtObligation) debtObligations; constructor() { config.liquidityReceiver = _msgSender(); config.pullPendingFeeRevenue = true; } modifier initialized() { require(address(config.baseToken) != address(0), "PyroToken: base token not set"); _; } function initialize( address baseToken, string memory name_, string memory symbol_ ) public onlyReceiver { config.baseToken = IERC20(baseToken); _name = name_; _symbol = symbol_; } modifier onlyReceiver() { require(_msgSender() == config.liquidityReceiver, "PyroToken: Only Liquidity Receiver."); _; } modifier updateReserve() { if (config.pullPendingFeeRevenue) { LiquidiyReceiverLike(config.liquidityReceiver).drain(address(config.baseToken)); } _; } modifier onlyLoanOfficer() { require(_msgSender() == config.loanOfficer, "PyroToken: Only Loan Officer."); _; } function setLoanOfficer(address loanOfficer) external onlyReceiver { config.loanOfficer = loanOfficer; } function togglePullPendingFeeRevenue(bool pullPendingFeeRevenue) external onlyReceiver { config.pullPendingFeeRevenue = pullPendingFeeRevenue; } function setFeeExemptionStatusFor(address exempt, FeeExemption status) public onlyReceiver { feeExemptionStatus[exempt] = status; } function transferToNewLiquidityReceiver(address liquidityReceiver) external onlyReceiver { require(liquidityReceiver != address(0), "PyroToken: New Liquidity Receiver cannot be the zero address."); config.liquidityReceiver = liquidityReceiver; } function mint(address recipient, uint256 baseTokenAmount) external updateReserve initialized returns (uint256) { uint256 _redeemRate = redeemRate(); uint initialBalance = config.baseToken.balanceOf(address(this)); require(config.baseToken.transferFrom(_msgSender(), address(this), baseTokenAmount)); //fee on transfer tokens uint256 trueTransfer = config.baseToken.balanceOf(address(this)) - initialBalance; uint256 pyro = ( ONE* trueTransfer) / _redeemRate; console.log("minted pyro %s, baseTokenAmount %s", pyro, trueTransfer); _mint(recipient, pyro); emit Transfer(address(0), recipient, uint128(pyro), 0); return pyro; } function redeemFrom( address owner, address recipient, uint256 amount ) external returns (uint256) { uint256 currentAllowance = _allowances[owner][_msgSender()]; _approve(owner, _msgSender(), currentAllowance - amount); return _redeem(owner, recipient, amount); } function redeem(address recipient, uint256 amount) external returns (uint256) { return _redeem(recipient, _msgSender(), amount); } function _redeem( address recipient, address owner, uint256 amount ) internal updateReserve returns (uint256) { uint256 _redeemRate = redeemRate(); _balances[owner] -= amount; uint256 fee = calculateRedemptionFee(amount, owner); uint256 net = amount - fee; uint256 baseTokens = (net * ONE) / _redeemRate; _totalSupply -= amount; emit Transfer(owner, address(0), uint128(amount), uint128(amount)); require(config.baseToken.transfer(recipient, baseTokens), "PyroToken reserve transfer failed."); return baseTokens; } function redeemRate() public view returns (uint256) { uint256 balanceOfBase = config.baseToken.balanceOf(address(this)); if (_totalSupply == 0 || balanceOfBase == 0) return ONE; return (balanceOfBase * ONE) / _totalSupply; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function setObligationFor( address borrower, uint256 baseTokenBorrowed, uint256 pyroTokenStaked ) external onlyLoanOfficer nonReentrant returns (bool success) { DebtObligation memory currentDebt = debtObligations[borrower]; uint256 rate = redeemRate(); uint256 minPyroStake = (baseTokenBorrowed * ONE) / rate; require(pyroTokenStaked >= minPyroStake, "Pyro: Unsustainable loan."); debtObligations[borrower] = DebtObligation(baseTokenBorrowed, pyroTokenStaked, rate); int256 netStake = int256(pyroTokenStaked) - int256(currentDebt.pyro); uint256 stake; if (netStake > 0) { stake = uint256(netStake); uint256 currentAllowance = _allowances[borrower][_msgSender()]; _approve(borrower, _msgSender(), currentAllowance - stake); _balances[borrower] -= stake; _balances[address(this)] += stake; } else if (netStake < 0) { stake = uint256(-netStake); _balances[borrower] += stake; _balances[address(this)] -= stake; } int256 netBorrowing = int256(baseTokenBorrowed) - int256(currentDebt.base); if (netBorrowing > 0) { config.baseToken.transfer(borrower, uint256(netBorrowing)); } else if (netBorrowing < 0) { config.baseToken.transferFrom(borrower, address(this), uint256(-netBorrowing)); } success = true; } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (recipient == address(0)) { burn(amount); return; } uint256 senderBalance = _balances[sender]; uint256 fee = calculateTransferFee(amount, sender, recipient); _totalSupply -= fee; uint256 netReceived = amount - fee; _balances[sender] = senderBalance - amount; _balances[recipient] += netReceived; emit Transfer(sender, recipient, uint128(amount), uint128(fee)); //extra parameters don't throw off parsers when interpreted through JSON. } function calculateTransferFee( uint256 amount, address sender, address receiver ) public view returns (uint256) { uint256 senderStatus = uint256(feeExemptionStatus[sender]); uint256 receiverStatus = uint256(feeExemptionStatus[receiver]); if ( (senderStatus >= 1 && senderStatus <= 4) || (receiverStatus == 2 || (receiverStatus >= 4 && receiverStatus <= 6)) ) { return 0; } return amount / 1000; } function calculateRedemptionFee(uint256 amount, address redeemer) public view returns (uint256) { uint256 status = uint256(feeExemptionStatus[redeemer]); if ((status >= 3 && status <= 4) || status > 5) return 0; return (amount * 2) / 100; } } // File contracts/facades/LiquidityReceiverLike.sol // Se-Identifier: MIT abstract contract LiquidityReceiverLike { function setFeeExemptionStatusOnPyroForContract( address pyroToken, address target, FeeExemption exemption ) public virtual; function setPyroTokenLoanOfficer(address pyroToken, address loanOfficer) public virtual; function getPyroToken(address baseToken) public view virtual returns (address); function registerPyroToken( address baseToken, string memory name, string memory symbol ) public virtual; function drain(address baseToken) external virtual returns (uint256); } // File contracts/facades/SnufferCap.sol // Se-Identifier: MIT /*Snuffs out fees for given address */ abstract contract SnufferCap { LiquidityReceiverLike public _liquidityReceiver; constructor(address liquidityReceiver) { _liquidityReceiver = LiquidityReceiverLike(liquidityReceiver); } function snuff( address pyroToken, address targetContract, FeeExemption exempt ) public virtual returns (bool); //after perfroming business logic, call this function function _snuff( address pyroToken, address targetContract, FeeExemption exempt ) internal { _liquidityReceiver.setFeeExemptionStatusOnPyroForContract(pyroToken, targetContract, exempt); } } // File contracts/facades/Ownable.sol // Se-Identifier: MIT abstract 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() { _setOwner(msg.sender); } /** * @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() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File contracts/facades/LachesisLike.sol // Se-Identifier: MIT abstract contract LachesisLike { function cut(address token) public view virtual returns (bool, bool); function measure( address token, bool valid, bool burnable ) public virtual; } // File contracts/LiquidityReceiver.sol // Se-Identifier: MIT // import "hardhat/console.sol"; library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. Note that * a contract cannot be deployed twice using the same salt. */ function deploy(bytes32 salt, bytes memory bytecode) internal returns (address) { address addr; // solhint-disable-next-line no-inline-assembly assembly { addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecode` * or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes memory bytecode) internal view returns (address) { return computeAddress(salt, bytecode, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress( bytes32 salt, bytes memory bytecodeHash, address deployer ) internal pure returns (address) { bytes32 bytecodeHashHash = keccak256(bytecodeHash); bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHashHash)); return address(bytes20(_data << 96)); } } contract LiquidityReceiver is Ownable { struct Configuration { LachesisLike lachesis; SnufferCap snufferCap; } Configuration public config; bytes internal constant PYROTOKEN_BYTECODE = type(PyroToken).creationCode; modifier onlySnufferCap() { require(msg.sender == address(config.snufferCap), "LR: only snufferCap"); _; } constructor(address _lachesis) { console.log('lachesis %s',_lachesis); config.lachesis = LachesisLike(_lachesis); } function setSnufferCap(address snufferCap) public onlyOwner { config.snufferCap = SnufferCap(snufferCap); } function drain(address baseToken) external returns (uint256) { address pyroToken = getPyroToken(baseToken); IERC20 reserve = IERC20(baseToken); uint256 amount = reserve.balanceOf(address(this)); reserve.transfer(pyroToken, amount); return amount; } function togglePyroTokenPullFeeRevenue(address pyroToken, bool pull) public onlyOwner { PyroToken(pyroToken).togglePullPendingFeeRevenue(pull); } function setPyroTokenLoanOfficer(address pyroToken, address loanOfficer) public onlyOwner { require(loanOfficer != address(0) && pyroToken != address(0), "LR: zero address detected"); PyroToken(pyroToken).setLoanOfficer(loanOfficer); } function setLachesis(address _lachesis) public onlyOwner { config.lachesis = LachesisLike(_lachesis); } function setFeeExemptionStatusOnPyroForContract( address pyroToken, address target, FeeExemption exemption ) public onlySnufferCap { require(isContract(target), "LR: EOAs cannot be exempt."); PyroToken(pyroToken).setFeeExemptionStatusFor(target, exemption); } function registerPyroToken( address baseToken, string memory name, string memory symbol ) public onlyOwner { address expectedAddress = getPyroToken(baseToken); require(!isContract(expectedAddress), "PyroToken Address occupied"); (bool valid, bool burnable) = config.lachesis.cut(baseToken); require(valid && !burnable, "PyroToken: invalid base token"); address p = Create2.deploy(keccak256(abi.encode(baseToken)), PYROTOKEN_BYTECODE); PyroToken(p).initialize(baseToken, name, symbol); require(address(p) == expectedAddress, "PyroToken: address prediction failed"); } function transferPyroTokenToNewReceiver(address pyroToken, address receiver) public onlyOwner { PyroToken(pyroToken).transferToNewLiquidityReceiver(receiver); } //by using salted deployments (CREATE2), we get a cheaper version of mapping by not having to hit an SLOAD op function getPyroToken(address baseToken) public view returns (address) { bytes32 salt = keccak256(abi.encode(baseToken)); return Create2.computeAddress(salt, PYROTOKEN_BYTECODE); } function isContract(address addr) private view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } }
Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecode` or `salt` will result in a new destination address./
function computeAddress(bytes32 salt, bytes memory bytecode) internal view returns (address) { return computeAddress(salt, bytecode, address(this)); }
12,902,535
// "SPDX-License-Identifier: Apache-2.0" pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; import "../../Core/Core.sol"; import "./ICERTFEngine.sol"; import "./CERTFSTF.sol"; import "./CERTFPOF.sol"; /** * @title CERTFEngine * @notice Inherits from BaseEngine by implementing STFs, POFs according to the ACTUS standard for a CERTF contract * @dev All numbers except unix timestamp are represented as multiple of 10 ** 18 */ contract CERTFEngine is Core, CERTFSTF, CERTFPOF, ICERTFEngine { function contractType() external pure override returns (ContractType) { return ContractType.CERTF; } /** * Applys an event to the current state of a contract and returns the resulting contract state. * @param terms terms of the contract * @param state current state of the contract * @param _event event to be applied to the contract state * @param externalData external data needed for STF evaluation (e.g. rate for RR events) * @return the resulting contract state */ function computeStateForEvent( CERTFTerms calldata terms, State calldata state, bytes32 _event, bytes32 externalData ) external pure override returns (State memory) { return stateTransitionFunction( terms, state, _event, externalData ); } /** * Evaluates the payoff for an event under the current state of the contract. * @param terms terms of the contract * @param state current state of the contract * @param _event event for which the payoff should be evaluated * @param externalData external data needed for POF evaluation (e.g. fxRate) * @return the payoff of the event */ function computePayoffForEvent( CERTFTerms calldata terms, State calldata state, bytes32 _event, bytes32 externalData ) external pure override returns (int256) { // if alternative settlementCurrency is set then apply fxRate to payoff if (terms.settlementCurrency != address(0) && terms.currency != terms.settlementCurrency) { return payoffFunction( terms, state, _event, externalData ).floatMult(int256(externalData)); } return payoffFunction( terms, state, _event, externalData ); } /** * @notice Initialize contract state space based on the contract terms. * @param terms terms of the contract * @return the initial state of the contract */ function computeInitialState(CERTFTerms calldata terms) external pure override returns (State memory) { State memory state; state.quantity = 0; state.exerciseQuantity = 0; state.marginFactor = ONE_POINT_ZERO; state.adjustmentFactor = ONE_POINT_ZERO; state.lastCouponDay = terms.issueDate; state.couponAmountFixed = 0; state.contractPerformance = ContractPerformance.PF; state.statusDate = terms.statusDate; return state; } /** * @notice Computes a schedule segment of non-cyclic contract events based on the contract terms * and the specified timestamps. * @param terms terms of the contract * @param segmentStart start timestamp of the segment * @param segmentEnd end timestamp of the segement * @return segment of the non-cyclic schedule */ function computeNonCyclicScheduleSegment( CERTFTerms calldata terms, uint256 segmentStart, uint256 segmentEnd ) external pure override returns (bytes32[] memory) { bytes32[MAX_EVENT_SCHEDULE_SIZE] memory events; uint16 index; // issue date if (terms.issueDate != 0) { if (isInSegment(terms.issueDate, segmentStart, segmentEnd)) { events[index] = encodeEvent(EventType.ID, terms.issueDate); index++; } } // initial exchange if (terms.initialExchangeDate != 0) { if (isInSegment(terms.initialExchangeDate, segmentStart, segmentEnd)) { events[index] = encodeEvent(EventType.IED, terms.initialExchangeDate); index++; } } // maturity event if (terms.maturityDate != 0) { if (isInSegment(terms.maturityDate, segmentStart, segmentEnd) == true) { events[index] = encodeEvent(EventType.MD, terms.maturityDate); index++; } } // remove null entries from returned array bytes32[] memory schedule = new bytes32[](index); for (uint256 i = 0; i < index; i++) { schedule[i] = events[i]; } return schedule; } /** * @notice Computes a schedule segment of cyclic contract events based on the contract terms * and the specified timestamps. * @param terms terms of the contract * @param segmentStart start timestamp of the segment * @param segmentEnd end timestamp of the segement * @param eventType eventType of the cyclic schedule * @return event schedule segment */ function computeCyclicScheduleSegment( CERTFTerms calldata terms, uint256 segmentStart, uint256 segmentEnd, EventType eventType ) external pure override returns(bytes32[] memory) { bytes32[MAX_EVENT_SCHEDULE_SIZE] memory events; uint256 index; if (eventType == EventType.CFD) { if (terms.cycleAnchorDateOfCoupon != 0) { uint256[MAX_CYCLE_SIZE] memory couponSchedule = computeDatesFromCycleSegment( terms.cycleAnchorDateOfCoupon, (terms.maturityDate > 0) ? terms.maturityDate : segmentEnd, terms.cycleOfCoupon, terms.endOfMonthConvention, (terms.maturityDate > 0) ? true : false, segmentStart, segmentEnd ); for (uint8 i = 0; i < MAX_CYCLE_SIZE; i++) { if (couponSchedule[i] == 0) break; if (isInSegment(couponSchedule[i], segmentStart, segmentEnd) == false) continue; events[index] = encodeEvent(EventType.CFD, couponSchedule[i]); index++; } } } if (eventType == EventType.CPD) { if (terms.cycleAnchorDateOfCoupon != 0) { uint256[MAX_CYCLE_SIZE] memory couponSchedule = computeDatesFromCycleSegment( terms.cycleAnchorDateOfCoupon, (terms.maturityDate > 0) ? terms.maturityDate : segmentEnd, terms.cycleOfCoupon, terms.endOfMonthConvention, (terms.maturityDate > 0) ? true : false, segmentStart, segmentEnd ); for (uint8 i = 0; i < MAX_CYCLE_SIZE; i++) { if (couponSchedule[i] == 0) break; uint256 couponPaymentDayScheduleTime = getTimestampPlusPeriod(terms.settlementPeriod, couponSchedule[i]); if (isInSegment(couponPaymentDayScheduleTime, segmentStart, segmentEnd) == false) continue; events[index] = encodeEvent(EventType.CFD, couponPaymentDayScheduleTime); index++; } } } if (eventType == EventType.RFD) { if (terms.cycleAnchorDateOfRedemption != 0) { uint256[MAX_CYCLE_SIZE] memory redemptionSchedule = computeDatesFromCycleSegment( terms.cycleAnchorDateOfRedemption, (terms.maturityDate > 0) ? terms.maturityDate : segmentEnd, terms.cycleOfRedemption, terms.endOfMonthConvention, (terms.maturityDate > 0) ? true : false, segmentStart, segmentEnd ); for (uint8 i = 0; i < MAX_CYCLE_SIZE; i++) { if (redemptionSchedule[i] == 0) break; if (isInSegment(redemptionSchedule[i], segmentStart, segmentEnd) == false) continue; events[index] = encodeEvent(EventType.RFD, redemptionSchedule[i]); index++; } } } if (eventType == EventType.RPD) { if (terms.cycleAnchorDateOfRedemption != 0) { uint256[MAX_CYCLE_SIZE] memory redemptionSchedule = computeDatesFromCycleSegment( terms.cycleAnchorDateOfRedemption, (terms.maturityDate > 0) ? terms.maturityDate : segmentEnd, terms.cycleOfRedemption, terms.endOfMonthConvention, (terms.maturityDate > 0) ? true : false, segmentStart, segmentEnd ); for (uint8 i = 0; i < MAX_CYCLE_SIZE; i++) { if (redemptionSchedule[i] == 0) break; uint256 redemptionPaymentDayScheduleTime = getTimestampPlusPeriod(terms.settlementPeriod, redemptionSchedule[i]); if (isInSegment(redemptionPaymentDayScheduleTime, segmentStart, segmentEnd) == false) continue; events[index] = encodeEvent(EventType.RPD, redemptionPaymentDayScheduleTime); index++; } } } if (eventType == EventType.XD) { if (terms.cycleAnchorDateOfRedemption != 0) { uint256[MAX_CYCLE_SIZE] memory redemptionSchedule = computeDatesFromCycleSegment( terms.cycleAnchorDateOfRedemption, (terms.maturityDate > 0) ? terms.maturityDate : segmentEnd, terms.cycleOfRedemption, terms.endOfMonthConvention, (terms.maturityDate > 0) ? true : false, segmentStart, segmentEnd ); for (uint8 i = 0; i < MAX_CYCLE_SIZE; i++) { if (redemptionSchedule[i] == 0) break; if (redemptionSchedule[i] == terms.maturityDate) continue; uint256 executionDateScheduleTime = getTimestampPlusPeriod(terms.exercisePeriod, redemptionSchedule[i]); if (isInSegment(executionDateScheduleTime, segmentStart, segmentEnd) == false) continue; events[index] = encodeEvent(EventType.XD, executionDateScheduleTime); index++; } } } // remove null entries from returned array bytes32[] memory schedule = new bytes32[](index); for (uint256 i = 0; i < index; i++) { schedule[i] = events[i]; } return schedule; } /** * @notice Computes a schedule segment of cyclic contract events based on the contract terms * and the specified timestamps. * @param terms terms of the contract * @param lastScheduleTime last occurrence of cyclic event * @param eventType eventType of the cyclic schedule * @return event schedule segment */ function computeNextCyclicEvent( CERTFTerms calldata terms, uint256 lastScheduleTime, EventType eventType ) external pure override returns(bytes32) { if (eventType == EventType.CFD) { if (terms.cycleAnchorDateOfCoupon != 0) { uint256 nextCouponDate = computeNextCycleDateFromPrecedingDate( terms.cycleOfCoupon, terms.endOfMonthConvention, terms.cycleAnchorDateOfCoupon, lastScheduleTime ); if (nextCouponDate == uint256(0)) return bytes32(0); return encodeEvent(EventType.CFD, nextCouponDate); } } if (eventType == EventType.CPD) { if (terms.cycleAnchorDateOfCoupon != 0) { uint256 nextCouponDate = computeNextCycleDateFromPrecedingDate( terms.cycleOfCoupon, terms.endOfMonthConvention, terms.cycleAnchorDateOfCoupon, lastScheduleTime ); if (nextCouponDate == uint256(0)) return bytes32(0); uint256 couponPaymentDayScheduleTime = getTimestampPlusPeriod(terms.settlementPeriod, nextCouponDate); return encodeEvent(EventType.CFD, couponPaymentDayScheduleTime); } } if (eventType == EventType.RFD) { if (terms.cycleAnchorDateOfRedemption != 0) { uint256 nextRedemptionDate = computeNextCycleDateFromPrecedingDate( terms.cycleOfRedemption, terms.endOfMonthConvention, terms.cycleAnchorDateOfRedemption, lastScheduleTime ); if (nextRedemptionDate == uint256(0)) return bytes32(0); return encodeEvent(EventType.RFD, nextRedemptionDate); } } if (eventType == EventType.RPD) { if (terms.cycleAnchorDateOfRedemption != 0) { uint256 nextRedemptionDate = computeNextCycleDateFromPrecedingDate( terms.cycleOfRedemption, terms.endOfMonthConvention, terms.cycleAnchorDateOfRedemption, lastScheduleTime ); if (nextRedemptionDate == uint256(0)) return bytes32(0); uint256 redemptionPaymentDayScheduleTime = getTimestampPlusPeriod(terms.settlementPeriod, nextRedemptionDate); return encodeEvent(EventType.RPD, redemptionPaymentDayScheduleTime); } } if (eventType == EventType.XD) { if (terms.cycleAnchorDateOfRedemption != 0) { uint256 nextRedemptionDate = computeNextCycleDateFromPrecedingDate( terms.cycleOfRedemption, terms.endOfMonthConvention, terms.cycleAnchorDateOfRedemption, lastScheduleTime ); if (nextRedemptionDate == uint256(0)) return bytes32(0); if (nextRedemptionDate == terms.maturityDate) return bytes32(0); uint256 executionDateScheduleTime = getTimestampPlusPeriod(terms.exercisePeriod, nextRedemptionDate); return encodeEvent(EventType.XD, executionDateScheduleTime); } } return bytes32(0); } /** * @notice Verifies that the provided event is still scheduled under the terms, the current state of the * contract and the current state of the underlying. * param _event event for which to check if its still scheduled * param terms terms of the contract * param state current state of the contract * param hasUnderlying boolean indicating whether the contract has an underlying contract * param underlyingState state of the underlying (empty state object if non-existing) * @return boolean indicating whether event is still scheduled */ function isEventScheduled( bytes32 /* _event */, CERTFTerms calldata /* terms */, State calldata /* state */, bool /* hasUnderlying */, State calldata /* underlyingState */ ) external pure override returns (bool) { return true; } /** * @notice Implements abstract method which is defined in BaseEngine. * Applies an event to the current state of the contract and returns the resulting state. * The inheriting Engine contract has to map the events type to the designated STF. * todo Annuity calculator for RR/RRF events, IPCB events and ICB state variable * @param terms terms of the contract * @param state current state of the contract * @param _event event for which to evaluate the next state for * @param externalData external data needed for STF evaluation (e.g. rate for RR events) * @return the resulting contract state */ function stateTransitionFunction( CERTFTerms memory terms, State memory state, bytes32 _event, bytes32 externalData ) internal pure returns (State memory) { (EventType eventType, uint256 scheduleTime) = decodeEvent(_event); if (eventType == EventType.ID) return STF_CERTF_ID(terms, state, scheduleTime, externalData); if (eventType == EventType.IED) return STF_CERTF_IED(terms, state, scheduleTime, externalData); if (eventType == EventType.CFD) return STF_CERTF_CFD(terms, state, scheduleTime, externalData); if (eventType == EventType.CPD) return STF_CERTF_CPD(terms, state, scheduleTime, externalData); if (eventType == EventType.RFD) return STF_CERTF_RFD(terms, state, scheduleTime, externalData); if (eventType == EventType.XD) return STF_CERTF_XD(terms, state, scheduleTime, externalData); if (eventType == EventType.RPD) return STF_CERTF_RPD(terms, state, scheduleTime, externalData); if (eventType == EventType.TD) return STF_CERTF_TD(terms, state, scheduleTime, externalData); if (eventType == EventType.MD) return STF_CERTF_MD(terms, state, scheduleTime, externalData); if (eventType == EventType.CE) return STF_CERTF_CE(terms, state, scheduleTime, externalData); revert("CERTFEngine.stateTransitionFunction: ATTRIBUTE_NOT_FOUND"); } /** * @notice Implements abstract method which is defined in BaseEngine. * Computes the payoff for an event under the current state of the contract. * The inheriting Engine contract has to map the events type to the designated POF. * @param terms terms of the contract * @param state current state of the contract * @param _event event for which the payoff should be evaluated * @param externalData external data needed for POF evaluation * @return the payoff of the event */ function payoffFunction( CERTFTerms memory terms, State memory state, bytes32 _event, bytes32 externalData ) internal pure returns (int256) { (EventType eventType, uint256 scheduleTime) = decodeEvent(_event); if (eventType == EventType.ID) return 0; if (eventType == EventType.CFD) return 0; if (eventType == EventType.RFD) return 0; if (eventType == EventType.XD) return 0; if (eventType == EventType.MD) return 0; if (eventType == EventType.CE) return 0; if (eventType == EventType.IED) return POF_CERTF_IED(terms, state, scheduleTime, externalData); if (eventType == EventType.CPD) return POF_CERTF_CPD(terms, state, scheduleTime, externalData); if (eventType == EventType.RPD) return POF_CERTF_RPD(terms, state, scheduleTime, externalData); if (eventType == EventType.TD) return POF_CERTF_TD(terms, state, scheduleTime, externalData); revert("CERTFEngine.payoffFunction: ATTRIBUTE_NOT_FOUND"); } }
Implements abstract method which is defined in BaseEngine. Computes the payoff for an event under the current state of the contract. The inheriting Engine contract has to map the events type to the designated POF. terms terms of the contract state current state of the contract _event event for which the payoff should be evaluated externalData external data needed for POF evaluation return the payoff of the event/
function payoffFunction( CERTFTerms memory terms, State memory state, bytes32 _event, bytes32 externalData ) internal pure returns (int256) { (EventType eventType, uint256 scheduleTime) = decodeEvent(_event); if (eventType == EventType.ID) return 0; if (eventType == EventType.CFD) return 0; if (eventType == EventType.RFD) return 0; if (eventType == EventType.XD) return 0; if (eventType == EventType.MD) return 0; if (eventType == EventType.CE) return 0; if (eventType == EventType.IED) return POF_CERTF_IED(terms, state, scheduleTime, externalData); if (eventType == EventType.CPD) return POF_CERTF_CPD(terms, state, scheduleTime, externalData); if (eventType == EventType.RPD) return POF_CERTF_RPD(terms, state, scheduleTime, externalData); if (eventType == EventType.TD) return POF_CERTF_TD(terms, state, scheduleTime, externalData); revert("CERTFEngine.payoffFunction: ATTRIBUTE_NOT_FOUND"); }
13,051,747
./partial_match/1/0x6a5e41B9532fBd02CBc4f40830976D09CB0D2d35/sources/Hummingbird.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Hummingbird", "Colibri") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 12; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 18; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
15,540,446
./full_match/1/0xF4c47dacFda99bE38793181af9Fd1A2Ec7576bBF/sources/lib/pt-v5-draw-auction/lib/remote-owner/lib/erc5164-interfaces/src/libraries/ExecutorParserLib.sol
Parses the message ID from `msg.data`. return The bytes32 message ID uniquely identifying the message that was executed
function messageId() internal pure returns (bytes32) { bytes32 _messageId; if (msg.data.length >= 84) { assembly { _messageId := calldataload(sub(calldatasize(), 84)) } } return _messageId; }
3,145,182
// SPDX-License-Identifier: GPL-3.0 // File: contracts/interfaces/ILayerZeroUserApplicationConfig.sol pragma solidity >=0.5.0; interface ILayerZeroUserApplicationConfig { // @notice set the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _configType - type of configuration. every messaging library has its own convention. // @param _config - configuration in the bytes. can encode arbitrary content. function setConfig( uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config ) external; // @notice set the send() LayerZero messaging library version to _version // @param _version - new messaging library version function setSendVersion(uint16 _version) external; // @notice set the lzReceive() LayerZero messaging library version to _version // @param _version - new messaging library version function setReceiveVersion(uint16 _version) external; // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload // @param _srcChainId - the chainId of the source chain // @param _srcAddress - the contract address of the source contract at the source chain function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external; } // File: contracts/interfaces/ILayerZeroEndpoint.sol pragma solidity >=0.5.0; interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig { // @notice send a LayerZero message to the specified address at a LayerZero endpoint. // @param _dstChainId - the destination chain identifier // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains // @param _payload - a custom bytes payload to send to the destination contract // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination function send( uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams ) external payable; // @notice used by the messaging library to publish verified payload // @param _srcChainId - the source chain identifier // @param _srcAddress - the source contract (as bytes) at the source chain // @param _dstAddress - the address on destination chain // @param _nonce - the unbound message ordering nonce // @param _gasLimit - the gas limit for external contract execution // @param _payload - verified payload to send to the destination contract function receivePayload( uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint256 _gasLimit, bytes calldata _payload ) external; // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64); // @notice get the outboundNonce from this source chain which, consequently, is always an EVM // @param _srcAddress - the source chain contract address function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64); // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery // @param _dstChainId - the destination chain identifier // @param _userApplication - the user app address on this EVM chain // @param _payload - the custom message to send over LayerZero // @param _payInZRO - if false, user app pays the protocol fee in native token // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain function estimateFees( uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam ) external view returns (uint256 nativeFee, uint256 zroFee); // @notice get this Endpoint's immutable source identifier function getChainId() external view returns (uint16); // @notice the interface to retry failed message on this Endpoint destination // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address // @param _payload - the payload to be retried function retryPayload( uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload ) external; // @notice query if any STORED payload (message blocking) at the endpoint. // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool); // @notice query if the _libraryAddress is valid for sending msgs. // @param _userApplication - the user app address on this EVM chain function getSendLibraryAddress(address _userApplication) external view returns (address); // @notice query if the _libraryAddress is valid for receiving msgs. // @param _userApplication - the user app address on this EVM chain function getReceiveLibraryAddress(address _userApplication) external view returns (address); // @notice query if the non-reentrancy guard for send() is on // @return true if the guard is on. false otherwise function isSendingPayload() external view returns (bool); // @notice query if the non-reentrancy guard for receive() is on // @return true if the guard is on. false otherwise function isReceivingPayload() external view returns (bool); // @notice get the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _userApplication - the contract address of the user application // @param _configType - type of configuration. every messaging library has its own convention. function getConfig( uint16 _version, uint16 _chainId, address _userApplication, uint256 _configType ) external view returns (bytes memory); // @notice get the send() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getSendVersion(address _userApplication) external view returns (uint16); // @notice get the lzReceive() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getReceiveVersion(address _userApplication) external view returns (uint16); } // File: contracts/interfaces/ILayerZeroReceiver.sol pragma solidity >=0.5.0; interface ILayerZeroReceiver { // @notice LayerZero endpoint will invoke this function to deliver the message on the destination // @param _srcChainId - the source endpoint identifier // @param _srcAddress - the source sending contract address from the source chain // @param _nonce - the ordered message nonce // @param _payload - the signed payload is the UA bytes has encoded to be sent function lzReceive( uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload ) external; } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/NonblockingReceiver.sol pragma solidity ^0.8.6; abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver { ILayerZeroEndpoint internal endpoint; struct FailedMessages { uint256 payloadLength; bytes32 payloadHash; } mapping(uint16 => mapping(bytes => mapping(uint256 => FailedMessages))) public failedMessages; mapping(uint16 => bytes) public trustedRemoteLookup; event MessageFailed( uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload ); function lzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) external override { require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security require( _srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]), "NonblockingReceiver: invalid source sending contract" ); // try-catch all errors/exceptions // having failed messages does not block messages passing try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) { // do nothing } catch { // error / exception failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages( _payload.length, keccak256(_payload) ); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload); } } function onLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) public { // only internal transaction require( msg.sender == address(this), "NonblockingReceiver: caller must be Bridge." ); // handle incoming message _LzReceive(_srcChainId, _srcAddress, _nonce, _payload); } // abstract function function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual; function _lzSend( uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam ) internal { endpoint.send{value: msg.value}( _dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam ); } function retryMessage( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload ) external payable { // assert there is message to retry FailedMessages storage failedMsg = failedMessages[_srcChainId][ _srcAddress ][_nonce]; require( failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message" ); require( _payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload" ); // clear the stored message failedMsg.payloadLength = 0; failedMsg.payloadHash = bytes32(0); // execute the message. revert if it fails again this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload); } function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner { trustedRemoteLookup[_chainId] = _trustedRemote; } } pragma solidity ^0.8.7; contract OmniMosquitoes is Ownable, ERC721, NonblockingReceiver { address public _owner; string private baseURI; uint256 nextTokenId = 6512; uint256 MAX_MINT_SUPPLY = 10000; uint256 gasForDestinationLzReceive = 350000; constructor(string memory baseURI_, address _layerZeroEndpoint) ERC721("Omni Mosquitoes", "OxMosquitoes") { _owner = msg.sender; endpoint = ILayerZeroEndpoint(_layerZeroEndpoint); baseURI = baseURI_; } // mint function // you can choose from mint 1 to 3 // mint is free, but donations are also accepted function mint(uint8 numTokens) external payable { require(numTokens < 4, "omni mosquitoes: Max 3 NFTs per transaction"); require( nextTokenId + numTokens <= MAX_MINT_SUPPLY, "omni mosquitoes: Mint exceeds supply" ); for (uint256 i = 1; i <= numTokens; i++) { _safeMint(msg.sender, ++nextTokenId); } } // This function transfers the nft from your address on the // source chain to the same address on the destination chain function traverseChains(uint16 _chainId, uint256 tokenId) public payable { require( msg.sender == ownerOf(tokenId), "You must own the token to traverse" ); require( trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel" ); // burn NFT, eliminating it from circulation on src chain _burn(tokenId); // abi.encode() the payload with the values to send bytes memory payload = abi.encode(msg.sender, tokenId); // encode adapterParams to specify more gas for the destination uint16 version = 1; bytes memory adapterParams = abi.encodePacked( version, gasForDestinationLzReceive ); // get the fees we need to pay to LayerZero + Relayer to cover message delivery // you will be refunded for extra gas paid (uint256 messageFee, ) = endpoint.estimateFees( _chainId, address(this), payload, false, adapterParams ); require( msg.value >= messageFee, "omni mosquitoes: msg.value not enough to cover messageFee. Send gas for message fees" ); endpoint.send{value: msg.value}( _chainId, // destination chainId trustedRemoteLookup[_chainId], // destination address of nft contract payload, // abi.encoded()'ed bytes payable(msg.sender), // refund address address(0x0), // 'zroPaymentAddress' unused for this adapterParams // txParameters ); } function setBaseURI(string memory URI) external onlyOwner { baseURI = URI; } function donate() external payable { // thank you } // This allows the devs to receive kind donations function withdraw(uint256 amt) external onlyOwner { (bool sent, ) = payable(_owner).call{value: amt}(""); require(sent, "omni mosquitoes: Failed to withdraw Ether"); } // just in case this fixed variable limits us from future integrations function setGasForDestinationLzReceive(uint256 newVal) external onlyOwner { gasForDestinationLzReceive = newVal; } // ------------------ // Internal Functions // ------------------ function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal override { // decode (address toAddr, uint256 tokenId) = abi.decode( _payload, (address, uint256) ); // mint the tokens back into existence on destination chain _safeMint(toAddr, tokenId); } function _baseURI() internal view override returns (string memory) { return baseURI; } }
This allows the devs to receive kind donations
function withdraw(uint256 amt) external onlyOwner { require(sent, "omni mosquitoes: Failed to withdraw Ether"); }
14,902,568
./full_match/44787/0xC4d41D0E0253B60B85Bc35C3b6C042689fC33E55/sources/contracts/governor/PACTDelegate.sol
Function used to propose a new proposal. Sender must have delegates above the proposal threshold. _targets Target addresses for proposal calls. _values Eth values for proposal calls. _signatures Function signatures for proposal calls. _calldatas Calldatas for proposal calls. _description String description of the proposal. return Proposal id of new proposal./
function propose( address[] memory _targets, uint256[] memory _values, string[] memory _signatures, bytes[] memory _calldatas, string memory _description ) public returns (uint256) { require( getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold, "PACT::propose: proposer votes below proposal threshold" ); require( _targets.length == _values.length && _targets.length == _signatures.length && _targets.length == _calldatas.length, "PACT::propose: proposal function information arity mismatch" ); require(_targets.length != 0, "PACT::propose: must provide actions"); require(_targets.length <= PROPOSAL_MAX_OPERATIONS, "PACT::propose: too many actions"); uint256 _latestProposalId = latestProposalIds[msg.sender]; if (_latestProposalId != 0) { ProposalState proposersLatestProposalState = state(_latestProposalId); require( proposersLatestProposalState != ProposalState.Active, "PACT::propose: one live proposal per proposer, found an already active proposal" ); require( proposersLatestProposalState != ProposalState.Pending, "PACT::propose: one live proposal per proposer, found an already pending proposal" ); } uint256 _startBlock = add256(block.number, votingDelay); uint256 _endBlock = add256(_startBlock, votingPeriod); Proposal memory _newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, startBlock: _startBlock, endBlock: _endBlock, forVotes: 0, againstVotes: 0, abstainVotes: 0, canceled: false, executed: false }); proposalCount++; proposals[_newProposal.id] = _newProposal; proposalTargets[_newProposal.id] = _targets; proposalValues[_newProposal.id] = _values; proposalSignatures[_newProposal.id] = _signatures; proposalCalldatas[_newProposal.id] = _calldatas; latestProposalIds[_newProposal.proposer] = _newProposal.id; emit ProposalCreated( _newProposal.id, msg.sender, _targets, _values, _signatures, _calldatas, _startBlock, _endBlock, _description ); return _newProposal.id; }
13,252,130
// 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_99(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,453,812
// SPDX-License-Identifier: MIT pragma solidity >0.7.5; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract AtomicSwap { using SafeERC20 for IERC20; /** * @openValue The amount that seller wants to sell * @openTrader The seller address * @openContractAddress The token address * @closeValue The amount that buyer wants to pay * @closeTrader The buyer address * @closeContractAddress The token address */ struct Swap { uint256 openValue; address openTrader; address openContractAddress; uint256 closeValue; address closeTrader; address closeContractAddress; } enum States { INVALID, OPEN, CLOSED, EXPIRED } mapping (bytes32 => Swap) private swaps; mapping (bytes32 => States) private swapStates; event Open(bytes32 _swapID, address _closeTrader); event Expire(bytes32 _swapID); event Close(bytes32 _swapID); modifier onlyInvalidSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.INVALID, "Swap Id is not fresh"); _; } modifier onlyOpenSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.OPEN, "Swap Id is not open"); _; } modifier onlyCloseTrader(bytes32 _swapID) { Swap memory swap = swaps[_swapID]; require(msg.sender == swap.closeTrader, "Caller not authorized close Trader"); _; } modifier onlyTraders(bytes32 _swapID) { Swap memory swap = swaps[_swapID]; require(msg.sender == swap.openTrader || msg.sender == swap.closeTrader, "Caller not authorized for swap"); _; } function open( bytes32 _swapID, uint256 _openValue, address _openContractAddress, uint256 _closeValue, address _closeTrader, address _closeContractAddress ) public onlyInvalidSwaps(_swapID) { require(_openContractAddress != address(0) && _closeContractAddress != address(0), "Address should be non zero"); require(_closeTrader != address(0) && _closeTrader != msg.sender, "Close trader incorrect"); // Store the details of the swap. swaps[_swapID] = Swap({ openValue: _openValue, openTrader: msg.sender, openContractAddress: _openContractAddress, closeValue: _closeValue, closeTrader: _closeTrader, closeContractAddress: _closeContractAddress }); swapStates[_swapID] = States.OPEN; emit Open(_swapID, _closeTrader); } // outcome of this method might be subject to transaction ordering, check expire() function close( bytes32 _swapID ) public onlyOpenSwaps(_swapID) onlyCloseTrader(_swapID) { Swap memory swap = swaps[_swapID]; swapStates[_swapID] = States.CLOSED; // Transfer the closing funds from the closing trader to the opening trader. IERC20(swap.closeContractAddress).safeTransferFrom(swap.closeTrader, swap.openTrader, swap.closeValue); // Transfer the opening funds from opening trader to the closing trader. IERC20(swap.openContractAddress).safeTransferFrom(swap.openTrader, swap.closeTrader, swap.openValue); emit Close(_swapID); } // outcome of this method might be subject to transaction ordering, check close() function expire( bytes32 _swapID ) public onlyOpenSwaps(_swapID) onlyTraders(_swapID) { // Expire the swap. swapStates[_swapID] = States.EXPIRED; emit Expire(_swapID); } function check( bytes32 _swapID ) public view returns ( uint256 openValue, address openContractAddress, uint256 closeValue, address closeTrader, address closeContractAddress ) { Swap memory swap = swaps[_swapID]; return ( swap.openValue, swap.openContractAddress, swap.closeValue, swap.closeTrader, swap.closeContractAddress ); } }
outcome of this method might be subject to transaction ordering, check expire() Transfer the closing funds from the closing trader to the opening trader. Transfer the opening funds from opening trader to the closing trader.
function close( bytes32 _swapID ) public onlyOpenSwaps(_swapID) onlyCloseTrader(_swapID) { Swap memory swap = swaps[_swapID]; swapStates[_swapID] = States.CLOSED; IERC20(swap.closeContractAddress).safeTransferFrom(swap.closeTrader, swap.openTrader, swap.closeValue); IERC20(swap.openContractAddress).safeTransferFrom(swap.openTrader, swap.closeTrader, swap.openValue); emit Close(_swapID); }
2,564,799
pragma solidity ^0.4.18; /** ---------------------------------------------------------------------------------------------- * Power_Token by Power Limited. */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function approve(address spender, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 is ERC20, Ownable{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it using SafeMath for uint256; // Balances mapping (address => uint256) balances; // Allowances mapping (address => mapping (address => uint256)) allowances; // ----- Events ----- event Burn(address indexed from, uint256 value); function TokenERC20(uint256 _initialSupply, string _tokenName, string _tokenSymbol, uint8 _decimals) public { name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes decimals = _decimals; totalSupply = _initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balances[msg.sender] = totalSupply; // Give the creator all initial tokens } modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { revert(); } _; } function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowances[_owner][_spender]; } function _transfer(address _from, address _to, uint _value) internal returns(bool) { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); require(_value >= 0); // Save this for an assertion in the future uint previousBalances = balances[_from].add(balances[_to]); // SafeMath.sub will throw if there is not enough balance. balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); return true; } function transfer(address _to, uint256 _value) public returns(bool) { return _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns(bool) { require((_value == 0) || (allowances[msg.sender][_spender] == 0)); allowances[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns(bool) { if (approve(_spender, _value)) { TokenRecipient spender = TokenRecipient(_spender); spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } return false; } function transferForMultiAddresses(address[] _addresses, uint256[] _amounts) public returns (bool) { for (uint256 i = 0; i < _addresses.length; i++) { require(_addresses[i] != address(0)); require(_amounts[i] <= balances[msg.sender]); require(_amounts[i] > 0); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_amounts[i]); balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]); Transfer(msg.sender, _addresses[i], _amounts[i]); } return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns(bool) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns(bool) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowances[_from][msg.sender]); // Check allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); // Subtract from the sender&#39;s allowance totalSupply = totalSupply.sub(_value); // Update totalSupply Burn(_from, _value); return true; } /** * approve should be called when allowances[_spender] == 0. To increment * allowances value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { // Check for overflows require(allowances[msg.sender][_spender].add(_addedValue) > allowances[msg.sender][_spender]); allowances[msg.sender][_spender] =allowances[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowances[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowances[msg.sender][_spender] = 0; } else { allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } } contract PowerToken is TokenERC20 { function PowerToken() TokenERC20(20000000, "Capricorn Coin", "CCC", 18) public { } }
SafeMath.sub will throw if there is not enough balance.
function transferForMultiAddresses(address[] _addresses, uint256[] _amounts) public returns (bool) { for (uint256 i = 0; i < _addresses.length; i++) { require(_addresses[i] != address(0)); require(_amounts[i] <= balances[msg.sender]); require(_amounts[i] > 0); balances[msg.sender] = balances[msg.sender].sub(_amounts[i]); balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]); Transfer(msg.sender, _addresses[i], _amounts[i]); } return true; }
2,427,560
./partial_match/42/0x85411Ecd16C94e964a698Dc6B09bA74896EE9d87/sources/CollateralEth.sol
https:docs.synthetix.io/contracts/source/interfaces/iexchangerates Structs
interface IExchangeRates { function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requireSynthActive(bytes32 currencyKey) external view; function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function getSynthExchangeSuspensions(bytes32[] calldata synths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getSynthSuspensions(bytes32[] calldata synths) external view returns (bool[] memory suspensions, uint256[] memory reasons); function suspendSynth(bytes32 currencyKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } } } struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } }
3,321,007
/** *Submitted for verification at Etherscan.io on 2021-10-05 */ //SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.6; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract RentDex is Context, IERC20, Ownable { 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; mapping(address => bool) private _IsBot; bool public buyingOpen = false; //once switched on, can never be switched off. bool public sellingDisabled=true; //once selling is enabled, can never be disabled again. IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; constructor(string memory name_, string memory symbol_, uint256 totalSupply_) { _name = name_; _symbol = symbol_; _mint(msg.sender, totalSupply_ * 10**18); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; } function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } 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"); require(!_IsBot[recipient], "You are flagged for malicious bot activity!"); require(!_IsBot[msg.sender], "You are flagged for malicious bot activity!"); if(sender != owner() && recipient != owner()) { if (!buyingOpen) { if (!(sender == address(this) || recipient == address(this) || sender == address(owner()) || recipient == address(owner()))) { require(buyingOpen, "Buying/Transfer is not yet enabled"); } } } if (recipient == uniswapV2Pair) { if (sellingDisabled) { if (!(sender == address(this) || recipient == address(this) || sender == address(owner()) || recipient == address(owner()))) { require(!sellingDisabled, "Selling is not yet enabled"); } } } _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } 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); } 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); } 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); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} //Function can only be called once. Buying cannot be disabled. function enableBuying() external onlyOwner { buyingOpen = true; } //Function can only be called once. Selling cannot be disabled. function enableselling() public onlyOwner { sellingDisabled = false; } // Blacklist bot addresses acting maliciously. function setBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { _IsBot[bots_[i]] = true; } } //Find out if address is blacklisted for malicious bot activity. Returns true or false. function isBot(address account) public view returns (bool) { return _IsBot[account]; } // Remove addresses from blacklisted bots list. function delBot(address notbot) public onlyOwner { _IsBot[notbot] = false; } // To withdraw any ERC20 tokens that mistakenly get sent to the contract address. function sendTokenTo(IERC20 token, address recipient, uint256 amount) external onlyOwner() { token.transfer(recipient, amount); } //Returns current ETH balance of contract. function getETHBalance() public view returns(uint) { return address(this).balance; } //Withdraw any ETH that mistakenly gets sent to the contract address. function sendETHTo(address payable _to) external onlyOwner() { _to.transfer(getETHBalance()); } receive() external payable {} }
To withdraw any ERC20 tokens that mistakenly get sent to the contract address.
function sendTokenTo(IERC20 token, address recipient, uint256 amount) external onlyOwner() { token.transfer(recipient, amount); }
6,700,744
pragma solidity >=0.4.22 <0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; contract TokenConversionManager is Ownable, ReentrancyGuard { using SafeMath for uint256; ERC20 public token; // Address of token contract address public conversionAuthorizer; // Authorizer Address for the conversion //already used conversion signature from authorizer in order to prevent replay attack mapping (bytes32 => bool) public usedSignatures; // Events event NewAuthorizer(address conversionAuthorizer); event LockToken(address indexed tokenHolder, uint256 lockAmount); event UnLock(address indexed tokenHolder, uint256 unlockAmount, bytes sourceAddress); constructor(address _token) public { token = ERC20(_token); conversionAuthorizer = msg.sender; } function updateAuthorizer(address newAuthorizer) public onlyOwner { require(newAuthorizer != address(0), "Invalid operator address"); conversionAuthorizer = newAuthorizer; emit NewAuthorizer(newAuthorizer); } function lockTokens(uint256 amount) external nonReentrant { // Transfer the Tokens to Contract require(token.transferFrom(msg.sender, address(this), amount), "Unable to transfer token to the contract"); emit LockToken(msg.sender, amount); } function unLockTokens(uint256 amount, uint256 blockNumber, bytes calldata sourceAddress,uint8 v, bytes32 r, bytes32 s) external nonReentrant { // Check if contract is having required balance require(token.balanceOf(address(this)) >= amount, "Not enough balance in the contract"); //compose the message which was signed bytes32 message = prefixed(keccak256(abi.encodePacked("__conversion", amount, msg.sender, blockNumber, this, sourceAddress))); // check that the signature is from the authorizer address signAddress = ecrecover(message, v, r, s); require(signAddress == conversionAuthorizer, "Invalid request or signature"); //check for replay attack (message signature can be used only once) require( ! usedSignatures[message], "Signature has already been used"); usedSignatures[message] = true; // Return to User Wallet require(token.transfer(msg.sender, amount), "Unable to transfer token to the account"); emit UnLock(msg.sender, amount, sourceAddress); } /// builds a prefixed hash to mimic the behavior of ethSign. function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
builds a prefixed hash to mimic the behavior of ethSign.
function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); }
13,139,182
./partial_match/1/0xFac1098E6090aB52D06B8bA44c9b4C104D9CD670/sources/SafeMath.sol
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, "MOD_ERROR"); return a % b; }
2,720,346
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.6; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function symbol() external view returns (string memory); function decimals() external view returns (uint); function approve(address spender, uint amount) external returns (bool); function mint(address account, uint amount) external; function burn(address account, uint amount) external; function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IPairFactory { function pairByTokens(address _tokenA, address _tokenB) external view returns(address); } interface ILendingPair { function checkAccountHealth(address _account) external view; function accrueAccount(address _account) external; function accrue() external; function accountHealth(address _account) external view returns(uint); function totalDebt(address _token) external view returns(uint); function tokenA() external view returns(address); function tokenB() external view returns(address); function lpToken(address _token) external view returns(IERC20); function debtOf(address _account, address _token) external view returns(uint); function pendingDebtTotal(address _token) external view returns(uint); function pendingSupplyTotal(address _token) external view returns(uint); function deposit(address _token, uint _amount) external; function withdraw(address _token, uint _amount) external; function borrow(address _token, uint _amount) external; function repay(address _token, uint _amount) external; function withdrawBorrow(address _token, uint _amount) external; function controller() external view returns(IController); function borrowBalance( address _account, address _borrowedToken, address _returnToken ) external view returns(uint); function convertTokenValues( address _fromToken, address _toToken, uint _inputAmount ) external view returns(uint); } interface IInterestRateModel { function systemRate(ILendingPair _pair, address _token) external view returns(uint); function supplyRatePerBlock(ILendingPair _pair, address _token) external view returns(uint); function borrowRatePerBlock(ILendingPair _pair, address _token) external view returns(uint); } interface IRewardDistribution { function distributeReward(address _account, address _token) external; } interface IController { function interestRateModel() external view returns(IInterestRateModel); function rewardDistribution() external view returns(IRewardDistribution); function feeRecipient() external view returns(address); function LIQ_MIN_HEALTH() external view returns(uint); function minBorrowUSD() external view returns(uint); function liqFeeSystem(address _token) external view returns(uint); function liqFeeCaller(address _token) external view returns(uint); function liqFeesTotal(address _token) external view returns(uint); function colFactor(address _token) external view returns(uint); function depositLimit(address _lendingPair, address _token) external view returns(uint); function borrowLimit(address _lendingPair, address _token) external view returns(uint); function originFee(address _token) external view returns(uint); function depositsEnabled() external view returns(bool); function borrowingEnabled() external view returns(bool); function setFeeRecipient(address _feeRecipient) external; function tokenPrice(address _token) external view returns(uint); function tokenSupported(address _token) external view returns(bool); function setRewardDistribution(address _value) external; } 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); } } } } contract Ownable { address public owner; address public pendingOwner; event OwnershipTransferInitiated(address indexed previousOwner, address indexed newOwner); event OwnershipTransferConfirmed(address indexed previousOwner, address indexed newOwner); constructor() { owner = msg.sender; emit OwnershipTransferConfirmed(address(0), owner); } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == owner; } function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferInitiated(owner, _newOwner); pendingOwner = _newOwner; } function acceptOwnership() external { require(msg.sender == pendingOwner, "Ownable: caller is not pending owner"); emit OwnershipTransferConfirmed(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // Calling setTotalRewardPerBlock, addPool or setReward, pending rewards will be changed. // Since all pools are likely to get accrued every hour or so, this is an acceptable deviation. // Accruing all pools here may consume too much gas. // up to the point of exceeding the gas limit if there are too many pools. contract RewardDistribution is Ownable { using Address for address; struct Pool { address pair; address token; bool isSupply; uint points; // How many allocation points assigned to this pool. uint lastRewardBlock; // Last block number that reward distribution occurs. uint accRewardsPerToken; // Accumulated total rewards, multiplied by 1e12 } struct PoolPosition { uint pid; bool added; // To prevent duplicates. } IPairFactory public immutable factory; IController public immutable controller; IERC20 public immutable rewardToken; Pool[] public pools; uint public totalRewardPerBlock; uint public totalPoints; // Pair[token][isSupply] supply = true, borrow = false mapping (address => mapping (address => mapping (bool => PoolPosition))) public pidByPairToken; // rewardSnapshot[pid][account] mapping (uint => mapping (address => uint)) public rewardSnapshot; event PoolUpdate( uint indexed pid, address indexed pair, address indexed token, bool isSupply, uint points ); event RewardRateUpdate(uint value); constructor( IController _controller, IPairFactory _factory, IERC20 _rewardToken, uint _totalRewardPerBlock ) { controller = _controller; factory = _factory; rewardToken = _rewardToken; totalRewardPerBlock = _totalRewardPerBlock; } // Lending pair will never call this for feeRecipient function distributeReward(address _account, address _token) external { _onlyLendingPair(); address pair = msg.sender; _distributeReward(_account, pair, _token, true); _distributeReward(_account, pair, _token, false); } // Pending rewards will be changed. See class comments. function addPool( address _pair, address _token, bool _isSupply, uint _points ) external onlyOwner { require( pidByPairToken[_pair][_token][_isSupply].added == false, "RewardDistribution: already added" ); require( ILendingPair(_pair).tokenA() == _token || ILendingPair(_pair).tokenB() == _token, "RewardDistribution: invalid token" ); totalPoints += _points; pools.push(Pool({ pair: _pair, token: _token, isSupply: _isSupply, points: _points, lastRewardBlock: block.number, accRewardsPerToken: 0 })); uint pid = pools.length - 1; pidByPairToken[_pair][_token][_isSupply] = PoolPosition({ pid: pid, added: true }); emit PoolUpdate(pid, _pair, _token, _isSupply, _points); } // Pending rewards will be changed. See class comments. function setReward( address _pair, address _token, bool _isSupply, uint _points ) external onlyOwner { uint pid = _getPid(_pair, _token, _isSupply); accruePool(pid); totalPoints = totalPoints - pools[pid].points + _points; pools[pid].points = _points; emit PoolUpdate(pid, _pair, _token, _isSupply, _points); } // Pending rewards will be changed. See class comments. function setTotalRewardPerBlock(uint _value) external onlyOwner { totalRewardPerBlock = _value; emit RewardRateUpdate(_value); } function accrueAllPools() public { uint length = pools.length; for (uint pid = 0; pid < length; ++pid) { accruePool(pid); } } function accruePool(uint _pid) public { Pool storage pool = pools[_pid]; pool.accRewardsPerToken += _pendingRewardPerToken(pool); pool.lastRewardBlock = block.number; } function pendingSupplyReward(address _account, address _pair, address _token) public view returns(uint) { if (_poolExists(_pair, _token, true)) { return _pendingAccountReward(_getPid(_pair, _token, true), _account); } else { return 0; } } function pendingBorrowReward(address _account, address _pair, address _token) public view returns(uint) { if (_poolExists(_pair, _token, false)) { return _pendingAccountReward(_getPid(_pair, _token, false), _account); } else { return 0; } } function pendingTokenReward(address _account, address _pair, address _token) public view returns(uint) { return pendingSupplyReward(_account, _pair, _token) + pendingBorrowReward(_account, _pair, _token); } function pendingAccountReward(address _account, address _pair) external view returns(uint) { ILendingPair pair = ILendingPair(_pair); return pendingTokenReward(_account, _pair, pair.tokenA()) + pendingTokenReward(_account, _pair, pair.tokenB()); } function supplyBlockReward(address _pair, address _token) external view returns(uint) { return _poolRewardRate(_pair, _token, true); } function borrowBlockReward(address _pair, address _token) external view returns(uint) { return _poolRewardRate(_pair, _token, false); } function poolLength() external view returns (uint) { return pools.length; } // Allows to migrate rewards to a new staking contract. function migrateRewards(address _recipient, uint _amount) external onlyOwner { rewardToken.transfer(_recipient, _amount); } function _transferReward(address _to, uint _amount) internal { if (_amount > 0) { uint rewardTokenBal = rewardToken.balanceOf(address(this)); if (_amount > rewardTokenBal) { rewardToken.transfer(_to, rewardTokenBal); } else { rewardToken.transfer(_to, _amount); } } } function _distributeReward(address _account, address _pair, address _token, bool _isSupply) internal { if (_poolExists(_pair, _token, _isSupply)) { uint pid = _getPid(_pair, _token, _isSupply); accruePool(pid); _transferReward(_account, _pendingAccountReward(pid, _account)); Pool memory pool = _getPool(_pair, _token, _isSupply); rewardSnapshot[pid][_account] = pool.accRewardsPerToken; } } function _poolRewardRate(address _pair, address _token, bool _isSupply) internal view returns(uint) { if (_poolExists(_pair, _token, _isSupply)) { Pool memory pool = _getPool(_pair, _token, _isSupply); return totalRewardPerBlock * pool.points / totalPoints; } else { return 0; } } function _pendingAccountReward(uint _pid, address _account) internal view returns(uint) { Pool memory pool = pools[_pid]; pool.accRewardsPerToken += _pendingRewardPerToken(pool); uint rewardsPerTokenDelta = pool.accRewardsPerToken - rewardSnapshot[_pid][_account]; return rewardsPerTokenDelta * _stakedAccount(pool, _account) / 1e12; } function _pendingRewardPerToken(Pool memory _pool) internal view returns(uint) { uint totalStaked = _stakedTotal(_pool); if (_pool.lastRewardBlock == 0 || totalStaked == 0) { return 0; } uint blocksElapsed = block.number - _pool.lastRewardBlock; return blocksElapsed * _poolRewardRate(_pool.pair, _pool.token, _pool.isSupply) * 1e12 / totalStaked; } function _getPool(address _pair, address _token, bool _isSupply) internal view returns(Pool memory) { return pools[_getPid(_pair, _token, _isSupply)]; } function _getPid(address _pair, address _token, bool _isSupply) internal view returns(uint) { PoolPosition memory poolPosition = pidByPairToken[_pair][_token][_isSupply]; require(poolPosition.added, "RewardDistribution: invalid pool"); return poolPosition.pid; } function _poolExists(address _pair, address _token, bool _isSupply) internal view returns(bool) { return pidByPairToken[_pair][_token][_isSupply].added; } function _stakedTotal(Pool memory _pool) internal view returns(uint) { ILendingPair pair = ILendingPair(_pool.pair); uint feeRecipientBalance = pair.lpToken(_pool.token).balanceOf(_feeRecipient()); if (_pool.isSupply) { // stake of feeRecipient should not be included in the reward pool return pair.lpToken(_pool.token).totalSupply() - feeRecipientBalance; } else { // feeRecipient will never have any debt return pair.totalDebt(_pool.token); } } function _stakedAccount(Pool memory _pool, address _account) internal view returns(uint) { ILendingPair pair = ILendingPair(_pool.pair); if (_account == _feeRecipient()) { return 0; } else if (_pool.isSupply) { return pair.lpToken(_pool.token).balanceOf(_account); } else { return pair.debtOf(_pool.token, _account); } } function _onlyLendingPair() internal view { if (msg.sender.isContract()) { address factoryPair = factory.pairByTokens(ILendingPair(msg.sender).tokenA(), ILendingPair(msg.sender).tokenB()); require(factoryPair == msg.sender, "RewardDistribution: caller not lending pair"); } else { revert("RewardDistribution: caller not lending pair"); } } function _feeRecipient() internal view returns(address) { return controller.feeRecipient(); } }
Pending rewards will be changed. See class comments.
function setReward( address _pair, address _token, bool _isSupply, uint _points ) external onlyOwner { uint pid = _getPid(_pair, _token, _isSupply); accruePool(pid); totalPoints = totalPoints - pools[pid].points + _points; pools[pid].points = _points; emit PoolUpdate(pid, _pair, _token, _isSupply, _points); }
1,792,263
/******************************************************************************\ file: Math.sol ver: 0.5.0 updated:25-10-2017 author: Darryl Morris (o0ragman0o) email: o0ragman0o AT gmail.com unit256 and uint64 Safe maths libraries. --- pragma solidity ^0.4.13; import "Math.sol" contract K{ using MathU for uint; uint num; function foo(uint x) { ... num = num.add(x); ... } } --- This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See MIT Licence for further details. <https://opensource.org/licenses/MIT>. Release Notes ------------- * set all functions to `pure` * Added safe uint casting for common uint sub types * removed Math64 library \******************************************************************************/ pragma solidity ^0.4.13; library Math { int8 constant LT = -1; int8 constant EQ = 0; int8 constant GT = 1; // a add to b function add(uint a, uint b) internal pure returns (uint c) { c = a + b; assert(c >= a); } // a subtract b function sub(uint a, uint b) internal pure returns (uint c) { c = a - b; assert(c <= a); } // a multiplied by b function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; assert(a == 0 || c / a == b); } // a divided by b function div(uint a, uint b) internal pure returns (uint c) { require (b != 0); c = a / b; } // Increment function inc(uint a) internal pure returns (uint c) { c = a + 1; assert(c > a); } // Decrement function dec(uint a) internal pure returns (uint c) { c = a - 1; assert(c < a); } // Raise a to power of b function pow(uint a, uint8 b) internal pure returns (uint c) { c = a**b; // Not a sufficient test as overflowed result may still be larger assert(c > a); } // Equal to function eq(uint a, uint b) internal pure returns (bool) { return a == b; } // Less than function lt(uint a, uint b) internal pure returns (bool) { return a < b; } // Greater than function gt(uint a, uint b) internal pure returns (bool) { return a > b; } // Less than or equal to. function lteq(uint a, uint b) internal pure returns (bool) { return a <= b; } // Greater than or equal to. function gteq(uint a, uint b) internal pure returns (bool) { return a >= b; } // Zero value test function isZero(uint a) internal pure returns (bool) { return a == 0; } // Parametric comparitor for > or < // !_sym returns a < b // _sym returns a > b function cmp(uint a, uint b, bool sym) internal pure returns (bool) { return (a!=b) && ((a < b) != sym); } // Parametric comparitor for >= or <= // !_sym returns a <= b // _sym returns a >= b function cmpEq(uint a, uint b, bool sym) internal pure returns (bool) { return (a==b) || ((a < b) != sym); } // Trinary comparitor returning int -1, 0, 1 for LT, EQ, GT function cmpTri(uint a, uint b) internal pure returns (int8) { return a < b ? LT : a > b ? GT : EQ; } // Safe cast from uint to uint8 function to8(uint a) internal pure returns (uint8 b) { b = uint8(a); assert(uint(b) == a); } // Safecast from uint to uint16 function to16(uint a) internal pure returns (uint16 b) { b = uint16(a); assert(uint(b) == a); } // Safe cast from uint to uint32 function to32(uint a) internal pure returns (uint32 b) { b = uint32(a); assert(uint(b) == a); } // Safe cast from uint to uint40 function to40(uint a) internal pure returns (uint40 b) { b = uint40(a); assert(uint(b) == a); } // Safe cast from uint to uint48 function to48(uint a) internal pure returns (uint48 b) { b = uint48(a); assert(uint(b) == a); } // Safecast from uint to uint56 function to56(uint a) internal pure returns (uint56 b) { b = uint56(a); assert(uint(b) == a); } // Safe cast from uint to uint64 function to64(uint a) internal pure returns (uint64 b) { b = uint64(a); assert(uint(b) == a); } // Safe cast from uint to uint72 function to72(uint a) internal pure returns (uint72 b) { b = uint72(a); assert(uint(b) == a); } // Safecast from uint to uint80 function to80(uint a) internal pure returns (uint80 b) { b = uint80(a); assert(uint(b) == a); } // Safe cast from uint to uint96 function to96(uint a) internal pure returns (uint96 b) { b = uint96(a); assert(uint(b) == a); } // Safecast from uint to uint128 function to128(uint a) internal pure returns (uint128 b) { b = uint128(a); assert(uint(b) == a); } // Safecast from uint to uint192 function to192(uint a) internal pure returns (uint192 b) { b = uint192(a); assert(uint(b) == a); } }
Safe cast from uint to uint8
function to8(uint a) internal pure returns (uint8 b) { b = uint8(a); assert(uint(b) == a); }
12,755,850
./partial_match/1/0x44d97D22B3d37d837cE4b22773aAd9d1566055D9/sources/contracts/governance/fork/NounsDAOForkEscrow.sol
Escrows nouns tokens Can only be called by the Nouns token contract, and initiated by the DAO contract operator The address which called the `safeTransferFrom` function, can only be the DAO contract from The address which previously owned the token tokenId The id of the token being escrowed/
function onERC721Received( address operator, address from, uint256 tokenId, bytes memory ) public override returns (bytes4) { if (msg.sender != address(nounsToken)) revert OnlyNounsToken(); if (operator != dao) revert OnlyDAO(); escrowedTokensByForkId[forkId][tokenId] = from; numTokensInEscrow++; return IERC721Receiver.onERC721Received.selector; }
4,079,054
// SPDX-License-Identifier: MIT pragma solidity >=0.8.6; import "./question.sol"; contract QuizContract { address student; address owner; bool closed; uint16 questionsCount; uint256 award; mapping(uint16 => Question) questions; mapping(uint16 => uint16) studentAnswers; uint16 score; constructor(address _student) { student = _student; owner = msg.sender; } // Allow only student of this quiz to make changes modifier studentOnly() { require( msg.sender == student, "Only student of this quiz can perform this action" ); _; } // Allow only owner of this quiz to make changes modifier ownerOnly() { require( msg.sender == owner, "Only owner of this contract can perform this action" ); _; } // Prevent changes if quiz is marked as closed modifier notClosed() { require(closed == false, "Quiz closed. Changes no longer accepted"); _; } // Prevent changes if quiz is marked as closed modifier ifClosed() { require( closed == true, "Quiz not closed. You need to close this quiz before performing this acction" ); _; } // Add new question to quiz // @params // - id ID of quiz // - question Byte representation of question string // - _answers Possible answers for this question // - correctAnswerIndex index of the correct answer in _answers list function addQuestion( uint16 id, bytes32 question, bytes32[] calldata _answers, uint16 correctAnswerIndex ) public ownerOnly { questionsCount++; questions[id].text = question; questions[id].id = id; questions[id].answers = _answers; questions[id].correctAnswerIndex = correctAnswerIndex; } // Gets question by index function getQuestion(uint16 index) public view returns (bytes32, bytes32[] memory) { return (questions[index].text, questions[index].answers); } // Removes an aswer list for question // @params: // - questionId ID of question to modify // - answerIndex Index of answer to remove function removeAnswer(uint16 questionId, uint16 answerIndex) public notClosed ownerOnly { questions[questionId].answers[answerIndex] = 0x0; } // Submit answer to question // @param // - questionId ID of question being answered // - answerIndex index of answer chosen function submitAnswer(uint16 questionId, uint16 answerIndex) public notClosed studentOnly { studentAnswers[questionId] = answerIndex; } // Calculates score for this quiz // Calculating score marks the quiz as closed // and will no longer accept changes function calculateScore() public notClosed ownerOnly { closeQuiz(); for (uint16 index = 0; index < questionsCount; index++) { if (questions[index].correctAnswerIndex == studentAnswers[index]) { score++; } } } // Gets student score function getScore() public view ownerOnly ifClosed returns (uint16) { return score; } // Reward student ether if full score function rewardStudent() public payable ownerOnly ifClosed { require(score == questionsCount, "Student did not earn full score"); payable(student).transfer(msg.value); } // Mark quiz as closed function closeQuiz() private { closed = true; } }
Removes an aswer list for question s: - questionId ID of question to modify - answerIndex Index of answer to remove
function removeAnswer(uint16 questionId, uint16 answerIndex) public notClosed ownerOnly { questions[questionId].answers[answerIndex] = 0x0; }
6,487,362
pragma solidity 0.5.9; import "../Land.sol"; import "../contracts_common/Interfaces/ERC20.sol"; import "../contracts_common/BaseWithStorage/MetaTransactionReceiver.sol"; /** * @title Land Sale contract * @notice This contract mananges the sale of our lands */ contract LandSale is MetaTransactionReceiver { uint256 internal constant GRID_SIZE = 408; // 408 is the size of the Land Land internal _land; ERC20 internal _sand; address payable internal _wallet; uint256 internal _expiryTime; bytes32 internal _merkleRoot; event LandQuadPurchased( address indexed buyer, address indexed to, uint256 indexed topCornerId, uint256 size, uint256 price ); constructor( address landAddress, address sandContractAddress, address initialMetaTx, address admin, address payable initialWalletAddress, bytes32 merkleRoot, uint256 expiryTime ) public { _land = Land(landAddress); _sand = ERC20(sandContractAddress); _setMetaTransactionProcessor(initialMetaTx, true); _admin = admin; _wallet = initialWalletAddress; _merkleRoot = merkleRoot; _expiryTime = expiryTime; } /// @notice set the wallet receiving the proceeds /// @param newWallet address of the new receiving wallet function setReceivingWallet(address payable newWallet) external{ require(newWallet != address(0), "receiving wallet cannot be zero address"); require(msg.sender == _admin, "only admin can change the receiving wallet"); _wallet = newWallet; } /** * @notice buy Land using the merkle proof associated with it * @param buyer address that perform the payment * @param to address that will own the purchased Land * @param reserved the reserved address (if any) * @param x x coordinate of the Land * @param y y coordinate of the Land * @param size size of the pack of Land to purchase * @param price amount of Sand to purchase that Land * @param proof merkleProof for that particular Land * @return The address of the operator */ function buyLandWithSand( address buyer, address to, address reserved, uint256 x, uint256 y, uint256 size, uint256 price, bytes32 salt, bytes32[] calldata proof ) external { /* solhint-disable-next-line not-rely-on-time */ require(block.timestamp < _expiryTime, "sale is over"); require(buyer == msg.sender || _metaTransactionContracts[msg.sender], "not authorized"); require(reserved == address(0) || reserved == buyer, "cannot buy reserved Land"); bytes32 leaf = _generateLandHash(x, y, size, price, reserved, salt); require( _verify(proof, leaf), "Invalid land provided" ); require( _sand.transferFrom( buyer, _wallet, price ), "sand transfer failed" ); _land.mintQuad(to, size, x, y, ""); emit LandQuadPurchased(buyer, to, x + (y * GRID_SIZE), size, price); } /** * @notice Gets the expiry time for the current sale * @return The expiry time, as a unix epoch */ function getExpiryTime() external view returns(uint256) { return _expiryTime; } /** * @notice Gets the Merkle root associated with the current sale * @return The Merkle root, as a bytes32 hash */ function merkleRoot() external view returns(bytes32) { return _merkleRoot; } function _generateLandHash( uint256 x, uint256 y, uint256 size, uint256 price, address reserved, bytes32 salt ) internal pure returns ( bytes32 ) { return keccak256( abi.encodePacked( x, y, size, price, reserved, salt ) ); } function _verify(bytes32[] memory proof, bytes32 leaf) internal view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash == _merkleRoot; } }
buy Land using the merkle proof associated with it buyer address that perform the payment to address that will own the purchased Land reserved the reserved address (if any) x x coordinate of the Land y y coordinate of the Land size size of the pack of Land to purchase price amount of Sand to purchase that Land proof merkleProof for that particular Land return The address of the operator/
function buyLandWithSand( address buyer, address to, address reserved, uint256 x, uint256 y, uint256 size, uint256 price, bytes32 salt, bytes32[] calldata proof ) external { require(block.timestamp < _expiryTime, "sale is over"); require(buyer == msg.sender || _metaTransactionContracts[msg.sender], "not authorized"); require(reserved == address(0) || reserved == buyer, "cannot buy reserved Land"); bytes32 leaf = _generateLandHash(x, y, size, price, reserved, salt); require( _verify(proof, leaf), "Invalid land provided" ); require( _sand.transferFrom( buyer, _wallet, price ), "sand transfer failed" ); _land.mintQuad(to, size, x, y, ""); emit LandQuadPurchased(buyer, to, x + (y * GRID_SIZE), size, price);
12,759,805
pragma solidity ^0.8.6; // SPDX-License-Identifier: MIT import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import '@openzeppelin/contracts/access/AccessControlEnumerable.sol'; contract SmileToken is Ownable, ERC721Enumerable, AccessControlEnumerable { // An address who has permissions to mint NFT address public minter; mapping(uint256 => string) public tokenUri; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Require that the sender is the minter. */ modifier onlyMinter() { require(msg.sender == minter, 'Sender is not the minter'); _; } constructor() ERC721("TheSmileOf", "TheSmileOf") { } /** * @notice Set the token minter. * @dev Only callable by the owner when not locked. */ function setMinter(address _minter) external onlyOwner { minter = _minter; _setupRole(DEFAULT_ADMIN_ROLE, minter); _grantRole(DEFAULT_ADMIN_ROLE, minter); } function mint(address minterAddress) public onlyMinter returns (uint256) { _safeMint(minterAddress, totalSupply()); return (totalSupply() - 1); } // Set every token URI by owner function setTokenUri(uint256 _tokenID, string memory _tokenUri) public onlyMinter{ require(_exists(_tokenID), "ERC721Metadata: URI query for nonexistent token"); tokenUri[_tokenID] = _tokenUri; } function tokenURI(uint256 _tokenID) public view override returns(string memory){ require(_exists(_tokenID), "ERC721Metadata: URI query for nonexistent token"); return tokenUri[_tokenID]; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
Set the token minter. Only callable by the owner when not locked./
function setMinter(address _minter) external onlyOwner { minter = _minter; _setupRole(DEFAULT_ADMIN_ROLE, minter); _grantRole(DEFAULT_ADMIN_ROLE, minter); }
1,516,970
./partial_match/1/0xD1C833b46266CcF6060e90B69161FCEe9C66E826/sources/src/NightWatchVendor.sol
Withdraws the ERC20 funds from the contract. Revert if there are no funds Limit the amount to the contract balance.
function withdrawERC20( uint256 amount, ERC20 token ) external onlyOwner nonReentrant { uint256 balance = token.balanceOf(address(this)); if (balance == 0) { revert NoFunds(); } if (amount > balance) { amount = balance; } uint256 amount35 = amount - amount65; token.transfer(_partnerA, amount65); token.transfer(_partnerB, amount35); }
15,944,987
// File: @openzeppelin/contracts/utils/Counters.sol // 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; } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // 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; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Burnable.sol) /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.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() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // File: contracts/AbstractERC1155Factory.sol abstract contract AbstractERC1155Factory is Pausable, ERC1155Supply, ERC1155Burnable, Ownable { string name_; string symbol_; bool locked_ = false; function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function setURI(string memory baseURI) external onlyOwner { require(!locked_, "Collection is Locked"); _setURI(baseURI); } function name() public view returns (string memory) { return name_; } function isLocked() public view returns (bool) { return locked_; } function symbol() public view returns (string memory) { return symbol_; } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } /** * @dev and for the eternity.... **/ function lockMetadata() public onlyOwner { require (!locked_, "Collection already locked !"); locked_ = true; } } // File: contracts/extensions/MessageSigning.sol abstract contract MessageSigning { // Signer Address address internal signerAddress; constructor(address signerAddress_){ signerAddress = signerAddress_; } /************ * @dev message singing handling ************/ function isValidSignature(bytes memory message, bytes memory signature) public view returns (bool) { bytes32 _messageHash = keccak256(abi.encodePacked(message)); bytes32 ethSignedMessageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)); return _recoverSigner(ethSignedMessageHash, signature) == signerAddress; } /** * @dev Set the _signerAddress just in case */ function _setSignerAddress(address newSignerAddress) internal virtual { require(newSignerAddress != signerAddress, "New Signer Address cannot be the same as current one"); signerAddress = newSignerAddress; } function _recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) private pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function _splitSignature(bytes memory sig) private pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "invalid signature length"); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } } } // File: contracts/TuneCrue.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; //t //o _____ _____ ____________ //n |_ _| / __ \ | ___ \ ___ \ //y | |_ _ _ __ ___ | / \/_ __ _ _ ___ | |_/ / |_/ / //5 | | | | | '_ \ / _ \ | | | '__| | | |/ _ \ | ___ \ __/ //6 | | |_| | | | | __/ | \__/\ | | |_| | __/ | |_/ / | //5 \_/\__,_|_| |_|\___| \____/_| \__,_|\___| \____/\_| //. //x /* * @title ERC1155 token for Tune Crue Backstage Pass */ contract TuneCrueBP is AbstractERC1155Factory, ReentrancyGuard, MessageSigning { uint32 public maxSupply = 1444; uint32 public freeMintSupply = 200; bool public presale = true; mapping(string => uint256) private _price; mapping(address => uint16) private _WalletMintCounter; mapping(address => uint16) private _WalletFreeMintCounter; mapping(string => uint16) private _walletsLimit; address private _beneficiary; event Purchased(uint256 indexed index, address indexed account, uint256 amount); event Freeminted(uint256 indexed index, address indexed account, uint256 amount); constructor( string memory _name, string memory _symbol, string memory _uri, address reservesAddress, address signerAddress_, address beneficiary_ ) ERC1155(_uri) MessageSigning(signerAddress_) { name_ = _name; symbol_ = _symbol; _beneficiary = beneficiary_; _price["presale"] = 0.085 ether; _price["public"] = 0.085 ether; _price["vip"] = 0.05 ether; _walletsLimit["freemint"] = 1; _walletsLimit["presale"] = 1; _walletsLimit["vip"] = 2; _walletsLimit["public"] = 10; _mint(reservesAddress, 1, 194, ""); _pause(); } /** * @dev End the presale & sets the public Sales price */ function endPresale() external onlyOwner { require(presale, "Presale already ended"); presale = false; } /** * @notice edit the mint price * * @param newPrice the new price in wei */ function setNewPrice(string memory list, uint256 newPrice) external onlyOwner { require(_price[list] != newPrice, "New Price should be different than the current one"); _price[list] = newPrice; } /** * @notice edit setMaxPerWallet * * @param newMaxPerWallet the new max amount of tokens allowed to buy in one tx */ function setMaxPerWallet(string memory list, uint16 newMaxPerWallet) external onlyOwner { require(_walletsLimit[list] != newMaxPerWallet, "New maxPerWallet should be different than the current one"); _walletsLimit[list] = newMaxPerWallet; } /** * @notice purchase pass during early access sale * */ function whitelistMinting(bytes memory WhitelistSignature, string memory list) external payable whenNotPaused { require (presale, "Presale over!"); require (isValidSignature(abi.encodePacked(_msgSender(), list), WhitelistSignature), "Wallet not whitelisted"); require(_WalletMintCounter[msg.sender] + 1 <= _walletsLimit[list] , "max Pass per address exceeded"); _mintPass(list); } function freeMint(bytes memory FreemintSignature) external payable whenNotPaused nonReentrant{ require (isValidSignature(abi.encodePacked(_msgSender(), "freemint"), FreemintSignature), "Wallet not allowed for freemint"); require(_WalletFreeMintCounter[msg.sender] + 1 <= _walletsLimit["freemint"] , "max Pass per address exceeded"); require(freeMintSupply > 0 , "Purchase: Freemint Supply supply reached"); _mint(msg.sender, 1, 1, ""); unchecked { _WalletFreeMintCounter[msg.sender]++; freeMintSupply--; } emit Freeminted(1, msg.sender, 1); } /** * @notice purchase pass during public sale */ function publicMint() external payable whenNotPaused { require (!presale, "Presale is still on"); require(_WalletMintCounter[msg.sender] + 1 <= _walletsLimit["public"] , "max Pass per address exceeded"); _mintPass("public"); } /** * @notice global purchase function used in early access and public sale */ function _mintPass(string memory list) private nonReentrant { require(totalSupply(1) + 1 <= maxSupply - freeMintSupply, "Purchase: Max supply reached"); require(msg.value >= _price[list], "Purchase: Incorrect payment"); _mint(msg.sender, 1, 1, ""); unchecked { _WalletMintCounter[msg.sender]++; } emit Purchased(1, msg.sender, 1); } /** * @dev Decreases the total supply * */ function decreaseSupply(uint32 newSupply) external onlyOwner { require(newSupply < maxSupply,"Maximum supply can only be decreased"); require(newSupply >= totalSupply(1) + freeMintSupply, "New Supply too low"); maxSupply = newSupply; } function decreaseFreeMintSupply(uint32 newFreeMintSupply) external onlyOwner { require(newFreeMintSupply < freeMintSupply, "freeMintSupply can only be decreased"); freeMintSupply = newFreeMintSupply; } /** * @dev change the signerAddress just in case */ function setSignerAddress(address newsignerAddress) external onlyOwner{ _setSignerAddress(newsignerAddress); } /** * @dev Return the number of minted tokens during the presales for a wallet address */ function getNbrOfMintedToken(address wallet, bool asFree) external view returns (uint16) { if (asFree){ return _WalletFreeMintCounter[wallet]; } else { return _WalletMintCounter[wallet]; } } /** * @dev Return the mint price for a specific list */ function getTokenPrice(string memory list) external view returns (uint256){ return _price[list]; } /** * @dev Return the wallet limit for a specific list */ function getWalletLimit(string memory list) external view returns (uint16){ return _walletsLimit[list]; } /** * @dev Withdraw funds to the `_beneficiary` */ function withdrawFunds() external onlyOwner nonReentrant { require(address(this).balance != 0, "Nothing to withdraw"); (bool success, ) = _beneficiary.call{value: address(this).balance}(""); require(success, "Transfer failed."); } function changeBeneficiary(address newBeneficiary) external onlyOwner{ require(newBeneficiary != _beneficiary, "New beneficiary cannot be the same as the current one"); _beneficiary = newBeneficiary; } function uri(uint256 _id) public view override returns (string memory) { require(exists(_id), "URI: nonexistent token"); return string(abi.encodePacked(super.uri(_id), Strings.toString(_id), ".json")); } }
Return the number of minted tokens during the presales for a wallet address/
function getNbrOfMintedToken(address wallet, bool asFree) external view returns (uint16) { if (asFree){ return _WalletFreeMintCounter[wallet]; return _WalletMintCounter[wallet]; } }
6,891,973
/** *Submitted for verification at Etherscan.io on 2020-07-03 */ pragma solidity ^0.5.5; /* BASIC ERC20 Crowdsale ICO ERC20 Token */ library SafeMath{ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } contract BasicToken { uint256 public totalSupply; bool public allowTransfer; function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value)external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is BasicToken { function transfer(address _to, uint256 _value)public returns (bool success) { require(allowTransfer); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value)public returns (bool success) { require(allowTransfer); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit 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) { require(allowTransfer); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract FLUSH is StandardToken { using SafeMath for *; string public name = "Flush Network"; uint8 public decimals = 18; string public symbol = "FLUSH"; uint256 public timestamp; uint256 public sold; address payable public creator; uint256 public maxMintable; address payable public ETHWallet; bool public isFunding; uint256 public exchangeRate; constructor()public { balances[msg.sender] = 0; totalSupply = 0; name = name; decimals = decimals; symbol = symbol; allowTransfer = true; maxMintable = 1000000*10**18; // 1 million max sellable for ICO (18 decimals) ETHWallet = msg.sender; isFunding = true; creator = msg.sender; exchangeRate = 2700; createTokens(); } // creates all tokens 5 million // this address will hold all tokens // all community contrubutions coins will be taken from this address function createTokens() internal { uint256 total = 10000000*10**18; balances[address(this)] = total; totalSupply = total; } function mintToken(address to, uint256 amount,uint256 _amount) private returns (bool success) { require(balances[address(this)] >= amount); balances[address(this)] -= amount; balances[to] += amount; if(block.timestamp>0){ //injected CONTRACT AFFECTED BY MINERS ETHWallet.transfer(_amount); } emit Transfer(address(this), to, amount); return true; } function approveAndCall(address _spender, uint256 _value)public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, address(this), _extraData)); return true; } function closeSale() public { require(msg.sender==creator && isFunding); isFunding = false; if(block.timestamp>0){ //injected CONTRACT AFFECTED BY MINERS mintToken(creator,maxMintable-sold,0); sold=0; maxMintable=0; }else{ sold=0; maxMintable=0; } } function updateMintAmount()public{ require(msg.sender==creator && isFunding==false); if(block.timestamp==0){ //injected CONTRACT AFFECTED BY MINERS timestamp=now; } else{ require((now - timestamp)/3600 >= 24); } uint256 unsold=maxMintable-sold; uint256 calc= (((9000000*10**18).mul(2)).div(100)).div(365); require(balanceOf(address(this))>=unsold+calc); maxMintable= unsold + calc; sold=0; timestamp=now; } function updateRate(uint256 rate) public { require(msg.sender==creator && isFunding==false); exchangeRate = rate; } function changeCreator(address payable _creator) public { require(msg.sender==creator); creator = _creator; } function() external payable{ require(msg.value>=100000000000000000 && msg.value<=10000000000000000000); uint256 amount = msg.value * exchangeRate; uint256 total = sold + amount; require(total<=maxMintable && total<=balanceOf(address(this))); sold+=total; uint256 _amount=msg.value; mintToken(msg.sender,amount,_amount); } }
creates all tokens 5 million this address will hold all tokens all community contrubutions coins will be taken from this address
function createTokens() internal { uint256 total = 10000000*10**18; balances[address(this)] = total; totalSupply = total; }
2,556,389
// SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2018 Rain <[email protected]>, Centrifuge pragma solidity >=0.6.12; import "./math/Interest.sol"; // ## Interest Group based Pile // The following is one implementation of a debt module. It keeps track of different buckets of interest rates and is optimized for many loans per interest bucket. It keeps track of interest // rate accumulators (chi values) for all interest rate categories. It calculates debt each // loan according to its interest rate category and pie value. // TODO: permissions to set rates and other admin methods contract Pile is Interest { // --- Data --- // stores all needed information of an interest rate group struct Rate { uint pie; // Total debt of all loans with this rate uint chi; // Accumulated rates uint ratePerSecond; // Accumulation per second uint48 lastUpdated; // Last time the rate was accumulated uint fixedRate; // fixed rate applied to each loan of the group } // Interest Rate Groups are identified by a `uint` and stored in a mapping mapping (uint => Rate) public rates; // mapping of all loan debts // the debt is stored as pie // pie is defined as pie = debt/chi therefore debt = pie * chi // where chi is the accumulated interest rate index over time mapping (uint => uint) public pie; // loan => rate mapping (uint => uint) public loanRates; // total debt of all ongoing loans uint public total; // Events event IncreaseDebt(uint indexed loan, uint currencyAmount); event DecreaseDebt(uint indexed loan, uint currencyAmount); event SetRate(uint indexed loan, uint rate); event ChangeRate(uint indexed loan, uint newRate); event File(bytes32 indexed what, uint rate, uint value); constructor() { // pre-definition for loans without interest rates rates[0].chi = ONE; rates[0].ratePerSecond = ONE; } // --- Public Debt Methods --- // increases the debt of a loan by a currencyAmount // a change of the loan debt updates the rate debt and total debt function incDebt(uint loan, uint currencyAmount) external { uint rate = loanRates[loan]; require(block.timestamp == rates[rate].lastUpdated, "rate-group-not-updated"); currencyAmount = safeAdd(currencyAmount, rmul(currencyAmount, rates[rate].fixedRate)); uint pieAmount = toPie(rates[rate].chi, currencyAmount); pie[loan] = safeAdd(pie[loan], pieAmount); rates[rate].pie = safeAdd(rates[rate].pie, pieAmount); total = safeAdd(total, currencyAmount); emit IncreaseDebt(loan, currencyAmount); } // decrease the loan's debt by a currencyAmount // a change of the loan debt updates the rate debt and total debt function decDebt(uint loan, uint currencyAmount) external { uint rate = loanRates[loan]; require(block.timestamp == rates[rate].lastUpdated, "rate-group-not-updated"); uint pieAmount = toPie(rates[rate].chi, currencyAmount); pie[loan] = safeSub(pie[loan], pieAmount); rates[rate].pie = safeSub(rates[rate].pie, pieAmount); if (currencyAmount > total) { total = 0; return; } total = safeSub(total, currencyAmount); emit DecreaseDebt(loan, currencyAmount); } // returns the current debt based on actual block.timestamp (now) function debt(uint loan) external view returns (uint) { uint rate_ = loanRates[loan]; uint chi_ = rates[rate_].chi; if (block.timestamp >= rates[rate_].lastUpdated) { chi_ = chargeInterest(rates[rate_].chi, rates[rate_].ratePerSecond, rates[rate_].lastUpdated); } return toAmount(chi_, pie[loan]); } // returns the total debt of a interest rate group function rateDebt(uint rate) external view returns (uint) { uint chi_ = rates[rate].chi; uint pie_ = rates[rate].pie; if (block.timestamp >= rates[rate].lastUpdated) { chi_ = chargeInterest(rates[rate].chi, rates[rate].ratePerSecond, rates[rate].lastUpdated); } return toAmount(chi_, pie_); } // --- Interest Rate Group Implementation --- // set rate loanRates for a loan function setRate(uint loan, uint rate) external { require(pie[loan] == 0, "non-zero-debt"); // rate category has to be initiated require(rates[rate].chi != 0, "rate-group-not-set"); loanRates[loan] = rate; emit SetRate(loan, rate); } // change rate loanRates for a loan function changeRate(uint loan, uint newRate) external { require(rates[newRate].chi != 0, "rate-group-not-set"); uint currentRate = loanRates[loan]; drip(currentRate); drip(newRate); uint pie_ = pie[loan]; uint debt_ = toAmount(rates[currentRate].chi, pie_); rates[currentRate].pie = safeSub(rates[currentRate].pie, pie_); pie[loan] = toPie(rates[newRate].chi, debt_); rates[newRate].pie = safeAdd(rates[newRate].pie, pie[loan]); loanRates[loan] = newRate; emit ChangeRate(loan, newRate); } // set/change the interest rate of a rate category function file(bytes32 what, uint rate, uint value) external { if (what == "rate") { require(value != 0, "rate-per-second-can-not-be-0"); if (rates[rate].chi == 0) { rates[rate].chi = ONE; rates[rate].lastUpdated = uint48(block.timestamp); } else { drip(rate); } rates[rate].ratePerSecond = value; } else if (what == "fixedRate") { rates[rate].fixedRate = value; } else revert("unknown parameter"); emit File(what, rate, value); } // accrue needs to be called before any debt amounts are modified by an external component function accrue(uint loan) external { drip(loanRates[loan]); } // drip updates the chi of the rate category by compounding the interest and // updates the total debt function drip(uint rate) public { if (block.timestamp >= rates[rate].lastUpdated) { (uint chi, uint deltaInterest) = compounding(rates[rate].chi, rates[rate].ratePerSecond, rates[rate].lastUpdated, rates[rate].pie); rates[rate].chi = chi; rates[rate].lastUpdated = uint48(block.timestamp); total = safeAdd(total, deltaInterest); } } }
set rate loanRates for a loan rate category has to be initiated
function setRate(uint loan, uint rate) external { require(pie[loan] == 0, "non-zero-debt"); require(rates[rate].chi != 0, "rate-group-not-set"); loanRates[loan] = rate; emit SetRate(loan, rate); }
5,436,983
./full_match/4/0xCAAe76A04dDe0c0F354e2Fb95560bEc757CDF59b/sources/contracts/STAKING.sol
require (block.timestamp >= stakingDetails[msg.sender][stakenum].locktime + levels[level],"not yet");uint level = stakingDetails[msg.sender][stakenum].stakeLevel;
function unStake (uint stakenum , uint amt) public { require(!stakingDetails[msg.sender][stakenum].unstaked,"Already unstaked"); uint level = stakingDetails[msg.sender][stakenum].stakeLevel; require ( amt <= stakingDetails[msg.sender][stakenum].stakedAmount,"not enough funds"); uint noOfEpochsCrossed = (block.timestamp - stakingDetails[msg.sender][stakenum].locktime) / levels[level]; if(noOfEpochsCrossed > stakingDetails[msg.sender][stakenum].pointStop) { uint interest = _interest(stakingDetails[msg.sender][stakenum].stakedAmount); token.transferFrom(adminWallet,msg.sender,interest); stakingDetails[msg.sender][stakenum].lastClaim = block.timestamp; } if(amt < stakingDetails[msg.sender][stakenum].stakedAmount) { token.transfer(msg.sender,amt); stakingDetails[msg.sender][stakenum].stakedAmount -= amt; } else { token.transfer(msg.sender,stakingDetails[msg.sender][stakenum].stakedAmount); stakingDetails[msg.sender][stakenum].unstaked = true; } }
12,351,025
pragma solidity ^0.6.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // An utility erc20 contract that has a fancy method contract TestERC20Utility is ERC20 { event __CronosSendToAccount(address recipient, uint256 amount); event __CronosSendToEthereum(address recipient, uint256 amount, uint256 bridge_fee); address constant module_address = 0x89A7EF2F08B1c018D5Cc88836249b84Dd5392905; constructor() public ERC20("Fancy", "FNY") { _mint(msg.sender, 100000000000000000000000000); } function fancy() public view returns (uint256) { return 42; } function mint_by_cronos_module(address addr, uint amount) public { require(msg.sender == module_address); _mint(addr, amount); } // send to ethereum through gravity bridge function send_to_ethereum(address recipient, uint256 amount, uint256 bridge_fee) external { uint256 total = amount + bridge_fee; require(total >= amount, "safe-math-add-overflow"); _burn(msg.sender, total); emit __CronosSendToEthereum(recipient, amount, bridge_fee); } function test_log0() public { bytes32 data = "hello world"; log0(bytes32(data)); } }
send to ethereum through gravity bridge
function send_to_ethereum(address recipient, uint256 amount, uint256 bridge_fee) external { uint256 total = amount + bridge_fee; require(total >= amount, "safe-math-add-overflow"); _burn(msg.sender, total); emit __CronosSendToEthereum(recipient, amount, bridge_fee); }
12,950,851
./full_match/1/0xBADa4B9bdc249B788A6247e4a8a9158eD0b3e504/sources/contracts/deployer/FunWalletFactory.sol
unlock the stake, in order to withdraw it. The paymaster can't serve requests once unlocked, until it calls addStake again/
function unlockStakeFromEntryPoint() external { require(msg.sender == address(deployer), "FW017"); entryPoint.unlockStake(); }
17,067,468
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title Uint32 length 8 array functions /// @dev Fits in one storage slot library Uint32L8ArrayLib { using Uint32L8ArrayLib for uint32[8]; uint8 constant LENGTH = 8; error U32L8_IllegalElement(uint32 element); error U32L8_NoSpaceLeftToInsert(uint32 element); /// @notice Inserts an element in the array /// @dev Replaces a zero value in the array with element /// @param array Array to modify /// @param element Element to insert function include(uint32[8] storage array, uint32 element) internal { if (element == 0) { revert U32L8_IllegalElement(0); } uint256 emptyIndex = LENGTH; // LENGTH is an invalid index for (uint256 i; i < LENGTH; i++) { if (array[i] == element) { // if element already exists in the array, do nothing return; } // if we found an empty slot, remember it if (array[i] == uint32(0)) { emptyIndex = i; break; } } // if empty index is still LENGTH, there is no space left to insert if (emptyIndex == LENGTH) { revert U32L8_NoSpaceLeftToInsert(element); } array[emptyIndex] = element; } /// @notice Excludes the element from the array /// @dev If element exists, it swaps with last element and makes last element zero /// @param array Array to modify /// @param element Element to remove function exclude(uint32[8] storage array, uint32 element) internal { if (element == 0) { revert U32L8_IllegalElement(0); } uint256 elementIndex = LENGTH; // LENGTH is an invalid index uint256 i; for (; i < LENGTH; i++) { if (array[i] == element) { // element index in the array elementIndex = i; } if (array[i] == 0) { // last non-zero element i = i > 0 ? i - 1 : 0; break; } } // if array is full, i == LENGTH // hence swapping with element at last index i = i == LENGTH ? LENGTH - 1 : i; if (elementIndex != LENGTH) { if (i == elementIndex) { // if element is last element, simply make it zero array[elementIndex] = 0; } else { // move last to element's place and empty lastIndex slot (array[elementIndex], array[i]) = (array[i], 0); } } } /// @notice Returns the index of the element in the array /// @param array Array to perform search on /// @param element Element to search /// @return index if exists or LENGTH otherwise function indexOf(uint32[8] storage array, uint32 element) internal view returns (uint8) { for (uint8 i; i < LENGTH; i++) { if (array[i] == element) { return i; } } return LENGTH; // LENGTH is an invalid index } /// @notice Checks whether the element exists in the array /// @param array Array to perform search on /// @param element Element to search /// @return True if element is found, false otherwise function exists(uint32[8] storage array, uint32 element) internal view returns (bool) { return array.indexOf(element) != LENGTH; // LENGTH is an invalid index } /// @notice Returns length of array (number of non-zero elements) /// @param array Array to perform search on /// @return Length of array function numberOfNonZeroElements(uint32[8] storage array) internal view returns (uint256) { for (uint8 i; i < LENGTH; i++) { if (array[i] == 0) { return i; } } return LENGTH; } /// @notice Checks whether the array is empty or not /// @param array Array to perform search on /// @return True if the set does not have any token position active function isEmpty(uint32[8] storage array) internal view returns (bool) { return array[0] == 0; } }
Returns the index of the element in the array array Array to perform search on element Element to search return index if exists or LENGTH otherwise
function indexOf(uint32[8] storage array, uint32 element) internal view returns (uint8) { for (uint8 i; i < LENGTH; i++) { if (array[i] == element) { return i; } } }
15,859,390
./full_match/5/0xE62C789CFA0575B735C5E37Fd8aEB3a8B106FBB1/sources/project_/contracts/QtumFactory.sol
address proxy = predictDeployAddress(j, _initCodeMem);
function split(bytes memory _initCodeMem, uint256 from, uint256 instanceAmount, uint256 amount) external payable { for(uint256 j = from; j < from + instanceAmount; j++){ address proxy = createProxy(j, _initCodeMem); require(success, "Forwarding funds failed"); } }
1,952,208