file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
//Address: 0xd35504e0f9bdcf8bca1ce7ec51fa2db514029182 //Contract name: EmployeesList //Balance: 0 Ether //Verification Date: 6/16/2017 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.11; contract Ownable { // replace with proper zeppelin smart contract address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) throw; _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) owner = newOwner; } } contract Destructable is Ownable { function selfdestruct() external onlyOwner { // free ethereum network state when done selfdestruct(owner); } } contract Math { // scale of the emulated fixed point operations uint constant public FP_SCALE = 10000; // todo: should be a library function divRound(uint v, uint d) internal constant returns(uint) { // round up if % is half or more return (v + (d/2)) / d; } function absDiff(uint v1, uint v2) public constant returns(uint) { return v1 > v2 ? v1 - v2 : v2 - v1; } function safeMul(uint a, uint b) public constant returns (uint) { uint c = a * b; if (a == 0 || c / a == b) return c; else throw; } function safeAdd(uint a, uint b) internal constant returns (uint) { uint c = a + b; if (!(c>=a && c>=b)) throw; return c; } } contract TimeSource { uint32 private mockNow; function currentTime() public constant returns (uint32) { // we do not support dates much into future (Sun, 07 Feb 2106 06:28:15 GMT) if (block.timestamp > 0xFFFFFFFF) throw; return mockNow > 0 ? mockNow : uint32(block.timestamp); } function mockTime(uint32 t) public { // no mocking on mainnet if (block.number > 3316029) throw; mockNow = t; } } contract BaseOptionsConverter { // modifiers are inherited, check `owned` pattern // http://solidity.readthedocs.io/en/develop/contracts.html#function-modifiers modifier onlyESOP() { if (msg.sender != getESOP()) throw; _; } // returns ESOP address which is a sole executor of exerciseOptions function function getESOP() public constant returns (address); // deadline for employees to exercise options function getExercisePeriodDeadline() public constant returns (uint32); // exercise of options for given employee and amount, please note that employee address may be 0 // .. in which case the intention is to burn options function exerciseOptions(address employee, uint poolOptions, uint extraOptions, uint bonusOptions, bool agreeToAcceleratedVestingBonusConditions) onlyESOP public; } contract ESOPTypes { // enums are numbered starting from 0. NotSet is used to check for non existing mapping enum EmployeeState { NotSet, WaitingForSignature, Employed, Terminated, OptionsExercised } // please note that 32 bit unsigned int is used to represent UNIX time which is enough to represent dates until Sun, 07 Feb 2106 06:28:15 GMT // storage access is optimized so struct layout is important struct Employee { // when vesting starts uint32 issueDate; // wait for employee signature until that time uint32 timeToSign; // date when employee was terminated, 0 for not terminated uint32 terminatedAt; // when fade out starts, 0 for not set, initally == terminatedAt // used only when calculating options returned to pool uint32 fadeoutStarts; // poolOptions employee gets (exit bonus not included) uint32 poolOptions; // extra options employee gets (neufund will not this option) uint32 extraOptions; // time at which employee got suspended, 0 - not suspended uint32 suspendedAt; // what is employee current status, takes 8 bit in storage EmployeeState state; // index in iterable mapping uint16 idx; // reserve until full 256 bit word //uint24 reserved; } function serializeEmployee(Employee memory employee) internal constant returns(uint[9] emp) { // guess what: struct layout in memory is aligned to word (256 bits) // struct in storage is byte aligned assembly { // return memory aligned struct as array of words // I just wonder when 'employee' memory is deallocated // answer: memory is not deallocated until transaction ends emp := employee } } function deserializeEmployee(uint[9] serializedEmployee) internal constant returns (Employee memory emp) { assembly { emp := serializedEmployee } } } contract CodeUpdateable is Ownable { // allows to stop operations and migrate data to different contract enum CodeUpdateState { CurrentCode, OngoingUpdate /*, CodeUpdated*/} CodeUpdateState public codeUpdateState; modifier isCurrentCode() { if (codeUpdateState != CodeUpdateState.CurrentCode) throw; _; } modifier inCodeUpdate() { if (codeUpdateState != CodeUpdateState.OngoingUpdate) throw; _; } function beginCodeUpdate() public onlyOwner isCurrentCode { codeUpdateState = CodeUpdateState.OngoingUpdate; } function cancelCodeUpdate() public onlyOwner inCodeUpdate { codeUpdateState = CodeUpdateState.CurrentCode; } function completeCodeUpdate() public onlyOwner inCodeUpdate { selfdestruct(owner); } } contract EmployeesList is ESOPTypes, Ownable, Destructable { event CreateEmployee(address indexed e, uint32 poolOptions, uint32 extraOptions, uint16 idx); event UpdateEmployee(address indexed e, uint32 poolOptions, uint32 extraOptions, uint16 idx); event ChangeEmployeeState(address indexed e, EmployeeState oldState, EmployeeState newState); event RemoveEmployee(address indexed e); mapping (address => Employee) employees; // addresses in the mapping, ever address[] public addresses; function size() external constant returns (uint16) { return uint16(addresses.length); } function setEmployee(address e, uint32 issueDate, uint32 timeToSign, uint32 terminatedAt, uint32 fadeoutStarts, uint32 poolOptions, uint32 extraOptions, uint32 suspendedAt, EmployeeState state) external onlyOwner returns (bool isNew) { uint16 empIdx = employees[e].idx; if (empIdx == 0) { // new element uint size = addresses.length; if (size == 0xFFFF) throw; isNew = true; empIdx = uint16(size + 1); addresses.push(e); CreateEmployee(e, poolOptions, extraOptions, empIdx); } else { isNew = false; UpdateEmployee(e, poolOptions, extraOptions, empIdx); } employees[e] = Employee({ issueDate: issueDate, timeToSign: timeToSign, terminatedAt: terminatedAt, fadeoutStarts: fadeoutStarts, poolOptions: poolOptions, extraOptions: extraOptions, suspendedAt: suspendedAt, state: state, idx: empIdx }); } function changeState(address e, EmployeeState state) external onlyOwner { if (employees[e].idx == 0) throw; ChangeEmployeeState(e, employees[e].state, state); employees[e].state = state; } function setFadeoutStarts(address e, uint32 fadeoutStarts) external onlyOwner { if (employees[e].idx == 0) throw; UpdateEmployee(e, employees[e].poolOptions, employees[e].extraOptions, employees[e].idx); employees[e].fadeoutStarts = fadeoutStarts; } function removeEmployee(address e) external onlyOwner returns (bool) { uint16 empIdx = employees[e].idx; if (empIdx > 0) { delete employees[e]; delete addresses[empIdx-1]; RemoveEmployee(e); return true; } return false; } function terminateEmployee(address e, uint32 issueDate, uint32 terminatedAt, uint32 fadeoutStarts, EmployeeState state) external onlyOwner { if (state != EmployeeState.Terminated) throw; Employee employee = employees[e]; // gets reference to storage and optimizer does it with one SSTORE if (employee.idx == 0) throw; ChangeEmployeeState(e, employee.state, state); employee.state = state; employee.issueDate = issueDate; employee.terminatedAt = terminatedAt; employee.fadeoutStarts = fadeoutStarts; employee.suspendedAt = 0; UpdateEmployee(e, employee.poolOptions, employee.extraOptions, employee.idx); } function getEmployee(address e) external constant returns (uint32, uint32, uint32, uint32, uint32, uint32, uint32, EmployeeState) { Employee employee = employees[e]; if (employee.idx == 0) throw; // where is struct zip/unzip :> return (employee.issueDate, employee.timeToSign, employee.terminatedAt, employee.fadeoutStarts, employee.poolOptions, employee.extraOptions, employee.suspendedAt, employee.state); } function hasEmployee(address e) external constant returns (bool) { // this is very inefficient - whole word is loaded just to check this return employees[e].idx != 0; } function getSerializedEmployee(address e) external constant returns (uint[9]) { Employee memory employee = employees[e]; if (employee.idx == 0) throw; return serializeEmployee(employee); } } contract ERC20OptionsConverter is BaseOptionsConverter, TimeSource, Math { // see base class for explanations address esopAddress; uint32 exercisePeriodDeadline; // balances for converted options mapping(address => uint) internal balances; // total supply uint public totalSupply; // deadline for all options conversion including company's actions uint32 public optionsConversionDeadline; event Transfer(address indexed from, address indexed to, uint value); modifier converting() { // throw after deadline if (currentTime() >= exercisePeriodDeadline) throw; _; } modifier converted() { // throw before deadline if (currentTime() < optionsConversionDeadline) throw; _; } function getESOP() public constant returns (address) { return esopAddress; } function getExercisePeriodDeadline() public constant returns(uint32) { return exercisePeriodDeadline; } function exerciseOptions(address employee, uint poolOptions, uint extraOptions, uint bonusOptions, bool agreeToAcceleratedVestingBonusConditions) public onlyESOP converting { // if no overflow on totalSupply, no overflows later uint options = safeAdd(safeAdd(poolOptions, extraOptions), bonusOptions); totalSupply = safeAdd(totalSupply, options); balances[employee] += options; Transfer(0, employee, options); } function transfer(address _to, uint _value) converted public { if (balances[msg.sender] < _value) throw; balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant public returns (uint balance) { return balances[_owner]; } function () payable { throw; } function ERC20OptionsConverter(address esop, uint32 exerciseDeadline, uint32 conversionDeadline) { esopAddress = esop; exercisePeriodDeadline = exerciseDeadline; optionsConversionDeadline = conversionDeadline; } } contract ESOPMigration { modifier onlyOldESOP() { if (msg.sender != getOldESOP()) throw; _; } // returns ESOP address which is a sole executor of exerciseOptions function function getOldESOP() public constant returns (address); // migrate employee to new ESOP contract, throws if not possible // in simplest case new ESOP contract should derive from this contract and implement abstract methods // employees list is available for inspection by employee address // poolOptions and extraOption is amount of options transferred out of old ESOP contract function migrate(address employee, uint poolOptions, uint extraOptions) onlyOldESOP public; } contract ESOP is ESOPTypes, CodeUpdateable, TimeSource { // employee changed events event ESOPOffered(address indexed employee, address company, uint32 poolOptions, uint32 extraOptions); event EmployeeSignedToESOP(address indexed employee); event SuspendEmployee(address indexed employee, uint32 suspendedAt); event ContinueSuspendedEmployee(address indexed employee, uint32 continuedAt, uint32 suspendedPeriod); event TerminateEmployee(address indexed employee, address company, uint32 terminatedAt, TerminationType termType); event EmployeeOptionsExercised(address indexed employee, address exercisedFor, uint32 poolOptions, bool disableAcceleratedVesting); event EmployeeMigrated(address indexed employee, address migration, uint pool, uint extra); // esop changed events event ESOPOpened(address company); event OptionsConversionOffered(address company, address converter, uint32 convertedAt, uint32 exercisePeriodDeadline); enum ESOPState { New, Open, Conversion } // use retrun codes until revert opcode is implemented enum ReturnCodes { OK, InvalidEmployeeState, TooLate, InvalidParameters, TooEarly } // event raised when return code from a function is not OK, when OK is returned one of events above is raised event ReturnCode(ReturnCodes rc); enum TerminationType { Regular, BadLeaver } //CONFIG OptionsCalculator public optionsCalculator; // total poolOptions in The Pool uint public totalPoolOptions; // ipfs hash of document establishing this ESOP bytes public ESOPLegalWrapperIPFSHash; // company address address public companyAddress; // root of immutable root of trust pointing to given ESOP implementation address public rootOfTrust; // default period for employee signature uint32 constant public MINIMUM_MANUAL_SIGN_PERIOD = 2 weeks; // STATE // poolOptions that remain to be assigned uint public remainingPoolOptions; // state of ESOP ESOPState public esopState; // automatically sets to Open (0) // list of employees EmployeesList public employees; // how many extra options inserted uint public totalExtraOptions; // when conversion event happened uint32 public conversionOfferedAt; // employee conversion deadline uint32 public exerciseOptionsDeadline; // option conversion proxy BaseOptionsConverter public optionsConverter; // migration destinations per employee mapping (address => ESOPMigration) private migrations; modifier hasEmployee(address e) { // will throw on unknown address if (!employees.hasEmployee(e)) throw; _; } modifier onlyESOPNew() { if (esopState != ESOPState.New) throw; _; } modifier onlyESOPOpen() { if (esopState != ESOPState.Open) throw; _; } modifier onlyESOPConversion() { if (esopState != ESOPState.Conversion) throw; _; } modifier onlyCompany() { if (companyAddress != msg.sender) throw; _; } function distributeAndReturnToPool(uint distributedOptions, uint idx) internal returns (uint) { // enumerate all employees that were offered poolOptions after than fromIdx -1 employee Employee memory emp; for (uint i = idx; i < employees.size(); i++) { address ea = employees.addresses(i); if (ea != 0) { // address(0) is deleted employee emp = _loademp(ea); // skip employees with no poolOptions and terminated employees if (emp.poolOptions > 0 && ( emp.state == EmployeeState.WaitingForSignature || emp.state == EmployeeState.Employed) ) { uint newoptions = optionsCalculator.calcNewEmployeePoolOptions(distributedOptions); emp.poolOptions += uint32(newoptions); distributedOptions -= uint32(newoptions); _saveemp(ea, emp); } } } return distributedOptions; } function removeEmployeesWithExpiredSignaturesAndReturnFadeout() onlyESOPOpen isCurrentCode public { // removes employees that didn't sign and sends their poolOptions back to the pool // computes fadeout for terminated employees and returns it to pool // we let anyone to call that method and spend gas on it Employee memory emp; uint32 ct = currentTime(); for (uint i = 0; i < employees.size(); i++) { address ea = employees.addresses(i); if (ea != 0) { // address(0) is deleted employee var ser = employees.getSerializedEmployee(ea); emp = deserializeEmployee(ser); // remove employees with expired signatures if (emp.state == EmployeeState.WaitingForSignature && ct > emp.timeToSign) { remainingPoolOptions += distributeAndReturnToPool(emp.poolOptions, i+1); totalExtraOptions -= emp.extraOptions; // actually this just sets address to 0 so iterator can continue employees.removeEmployee(ea); } // return fadeout to pool if (emp.state == EmployeeState.Terminated && ct > emp.fadeoutStarts) { var (returnedPoolOptions, returnedExtraOptions) = optionsCalculator.calculateFadeoutToPool(ct, ser); if (returnedPoolOptions > 0 || returnedExtraOptions > 0) { employees.setFadeoutStarts(ea, ct); // options from fadeout are not distributed to other employees but returned to pool remainingPoolOptions += returnedPoolOptions; // we maintain extraPool for easier statistics totalExtraOptions -= returnedExtraOptions; } } } } } function openESOP(uint32 pTotalPoolOptions, bytes pESOPLegalWrapperIPFSHash) external onlyCompany onlyESOPNew isCurrentCode returns (ReturnCodes) { // options are stored in unit32 if (pTotalPoolOptions > 1100000 || pTotalPoolOptions < 10000) { return _logerror(ReturnCodes.InvalidParameters); } totalPoolOptions = pTotalPoolOptions; remainingPoolOptions = totalPoolOptions; ESOPLegalWrapperIPFSHash = pESOPLegalWrapperIPFSHash; esopState = ESOPState.Open; ESOPOpened(companyAddress); return ReturnCodes.OK; } function offerOptionsToEmployee(address e, uint32 issueDate, uint32 timeToSign, uint32 extraOptions, bool poolCleanup) external onlyESOPOpen onlyCompany isCurrentCode returns (ReturnCodes) { // do not add twice if (employees.hasEmployee(e)) { return _logerror(ReturnCodes.InvalidEmployeeState); } if (timeToSign < currentTime() + MINIMUM_MANUAL_SIGN_PERIOD) { return _logerror(ReturnCodes.TooLate); } if (poolCleanup) { // recover poolOptions for employees with expired signatures // return fade out to pool removeEmployeesWithExpiredSignaturesAndReturnFadeout(); } uint poolOptions = optionsCalculator.calcNewEmployeePoolOptions(remainingPoolOptions); if (poolOptions > 0xFFFFFFFF) throw; Employee memory emp = Employee({ issueDate: issueDate, timeToSign: timeToSign, terminatedAt: 0, fadeoutStarts: 0, poolOptions: uint32(poolOptions), extraOptions: extraOptions, suspendedAt: 0, state: EmployeeState.WaitingForSignature, idx: 0 }); _saveemp(e, emp); remainingPoolOptions -= poolOptions; totalExtraOptions += extraOptions; ESOPOffered(e, companyAddress, uint32(poolOptions), extraOptions); return ReturnCodes.OK; } // todo: implement group add someday, however func distributeAndReturnToPool gets very complicated // todo: function calcNewEmployeePoolOptions(uint remaining, uint8 groupSize) // todo: function addNewEmployeesToESOP(address[] emps, uint32 issueDate, uint32 timeToSign) function offerOptionsToEmployeeOnlyExtra(address e, uint32 issueDate, uint32 timeToSign, uint32 extraOptions) external onlyESOPOpen onlyCompany isCurrentCode returns (ReturnCodes) { // do not add twice if (employees.hasEmployee(e)) { return _logerror(ReturnCodes.InvalidEmployeeState); } if (timeToSign < currentTime() + MINIMUM_MANUAL_SIGN_PERIOD) { return _logerror(ReturnCodes.TooLate); } Employee memory emp = Employee({ issueDate: issueDate, timeToSign: timeToSign, terminatedAt: 0, fadeoutStarts: 0, poolOptions: 0, extraOptions: extraOptions, suspendedAt: 0, state: EmployeeState.WaitingForSignature, idx: 0 }); _saveemp(e, emp); totalExtraOptions += extraOptions; ESOPOffered(e, companyAddress, 0, extraOptions); return ReturnCodes.OK; } function increaseEmployeeExtraOptions(address e, uint32 extraOptions) external onlyESOPOpen onlyCompany isCurrentCode hasEmployee(e) returns (ReturnCodes) { Employee memory emp = _loademp(e); if (emp.state != EmployeeState.Employed && emp.state != EmployeeState.WaitingForSignature) { return _logerror(ReturnCodes.InvalidEmployeeState); } emp.extraOptions += extraOptions; _saveemp(e, emp); totalExtraOptions += extraOptions; ESOPOffered(e, companyAddress, 0, extraOptions); return ReturnCodes.OK; } function employeeSignsToESOP() external hasEmployee(msg.sender) onlyESOPOpen isCurrentCode returns (ReturnCodes) { Employee memory emp = _loademp(msg.sender); if (emp.state != EmployeeState.WaitingForSignature) { return _logerror(ReturnCodes.InvalidEmployeeState); } uint32 t = currentTime(); if (t > emp.timeToSign) { remainingPoolOptions += distributeAndReturnToPool(emp.poolOptions, emp.idx); totalExtraOptions -= emp.extraOptions; employees.removeEmployee(msg.sender); return _logerror(ReturnCodes.TooLate); } employees.changeState(msg.sender, EmployeeState.Employed); EmployeeSignedToESOP(msg.sender); return ReturnCodes.OK; } function toggleEmployeeSuspension(address e, uint32 toggledAt) external onlyESOPOpen onlyCompany hasEmployee(e) isCurrentCode returns (ReturnCodes) { Employee memory emp = _loademp(e); if (emp.state != EmployeeState.Employed) { return _logerror(ReturnCodes.InvalidEmployeeState); } if (emp.suspendedAt == 0) { //suspend action emp.suspendedAt = toggledAt; SuspendEmployee(e, toggledAt); } else { if (emp.suspendedAt > toggledAt) { return _logerror(ReturnCodes.TooLate); } uint32 suspendedPeriod = toggledAt - emp.suspendedAt; // move everything by suspension period by changing issueDate emp.issueDate += suspendedPeriod; emp.suspendedAt = 0; ContinueSuspendedEmployee(e, toggledAt, suspendedPeriod); } _saveemp(e, emp); return ReturnCodes.OK; } function terminateEmployee(address e, uint32 terminatedAt, uint8 terminationType) external onlyESOPOpen onlyCompany hasEmployee(e) isCurrentCode returns (ReturnCodes) { // terminates an employee TerminationType termType = TerminationType(terminationType); Employee memory emp = _loademp(e); // todo: check termination time against issueDate if (terminatedAt < emp.issueDate) { return _logerror(ReturnCodes.InvalidParameters); } if (emp.state == EmployeeState.WaitingForSignature) termType = TerminationType.BadLeaver; else if (emp.state != EmployeeState.Employed) { return _logerror(ReturnCodes.InvalidEmployeeState); } // how many poolOptions returned to pool uint returnedOptions; uint returnedExtraOptions; if (termType == TerminationType.Regular) { // regular termination, compute suspension if (emp.suspendedAt > 0 && emp.suspendedAt < terminatedAt) emp.issueDate += terminatedAt - emp.suspendedAt; // vesting applies returnedOptions = emp.poolOptions - optionsCalculator.calculateVestedOptions(terminatedAt, emp.issueDate, emp.poolOptions); returnedExtraOptions = emp.extraOptions - optionsCalculator.calculateVestedOptions(terminatedAt, emp.issueDate, emp.extraOptions); employees.terminateEmployee(e, emp.issueDate, terminatedAt, terminatedAt, EmployeeState.Terminated); } else if (termType == TerminationType.BadLeaver) { // bad leaver - employee is kicked out from ESOP, return all poolOptions returnedOptions = emp.poolOptions; returnedExtraOptions = emp.extraOptions; employees.removeEmployee(e); } remainingPoolOptions += distributeAndReturnToPool(returnedOptions, emp.idx); totalExtraOptions -= returnedExtraOptions; TerminateEmployee(e, companyAddress, terminatedAt, termType); return ReturnCodes.OK; } function offerOptionsConversion(BaseOptionsConverter converter) external onlyESOPOpen onlyCompany isCurrentCode returns (ReturnCodes) { uint32 offerMadeAt = currentTime(); if (converter.getExercisePeriodDeadline() - offerMadeAt < MINIMUM_MANUAL_SIGN_PERIOD) { return _logerror(ReturnCodes.TooLate); } // exerciseOptions must be callable by us if (converter.getESOP() != address(this)) { return _logerror(ReturnCodes.InvalidParameters); } // return to pool everything we can removeEmployeesWithExpiredSignaturesAndReturnFadeout(); // from now vesting and fadeout stops, no new employees may be added conversionOfferedAt = offerMadeAt; exerciseOptionsDeadline = converter.getExercisePeriodDeadline(); optionsConverter = converter; // this is very irreversible esopState = ESOPState.Conversion; OptionsConversionOffered(companyAddress, address(converter), offerMadeAt, exerciseOptionsDeadline); return ReturnCodes.OK; } function exerciseOptionsInternal(uint32 calcAtTime, address employee, address exerciseFor, bool disableAcceleratedVesting) internal returns (ReturnCodes) { Employee memory emp = _loademp(employee); if (emp.state == EmployeeState.OptionsExercised) { return _logerror(ReturnCodes.InvalidEmployeeState); } // if we are burning options then send 0 if (exerciseFor != address(0)) { var (pool, extra, bonus) = optionsCalculator.calculateOptionsComponents(serializeEmployee(emp), calcAtTime, conversionOfferedAt, disableAcceleratedVesting); } // call before options conversion contract to prevent re-entry employees.changeState(employee, EmployeeState.OptionsExercised); // exercise options in the name of employee and assign those to exerciseFor optionsConverter.exerciseOptions(exerciseFor, pool, extra, bonus, !disableAcceleratedVesting); EmployeeOptionsExercised(employee, exerciseFor, uint32(pool + extra + bonus), !disableAcceleratedVesting); return ReturnCodes.OK; } function employeeExerciseOptions(bool agreeToAcceleratedVestingBonusConditions) external onlyESOPConversion hasEmployee(msg.sender) isCurrentCode returns (ReturnCodes) { uint32 ct = currentTime(); if (ct > exerciseOptionsDeadline) { return _logerror(ReturnCodes.TooLate); } return exerciseOptionsInternal(ct, msg.sender, msg.sender, !agreeToAcceleratedVestingBonusConditions); } function employeeDenyExerciseOptions() external onlyESOPConversion hasEmployee(msg.sender) isCurrentCode returns (ReturnCodes) { uint32 ct = currentTime(); if (ct > exerciseOptionsDeadline) { return _logerror(ReturnCodes.TooLate); } // burn the options by sending to 0 return exerciseOptionsInternal(ct, msg.sender, address(0), true); } function exerciseExpiredEmployeeOptions(address e, bool disableAcceleratedVesting) external onlyESOPConversion onlyCompany hasEmployee(e) isCurrentCode returns (ReturnCodes) { // company can convert options for any employee that did not converted (after deadline) uint32 ct = currentTime(); if (ct <= exerciseOptionsDeadline) { return _logerror(ReturnCodes.TooEarly); } return exerciseOptionsInternal(ct, e, companyAddress, disableAcceleratedVesting); } function allowEmployeeMigration(address employee, ESOPMigration migration) external onlyESOPOpen hasEmployee(employee) onlyCompany isCurrentCode returns (ReturnCodes) { if (address(migration) == 0) throw; // only employed and terminated users may migrate Employee memory emp = _loademp(employee); if (emp.state != EmployeeState.Employed && emp.state != EmployeeState.Terminated) { return _logerror(ReturnCodes.InvalidEmployeeState); } migrations[employee] = migration; // can be cleared with 0 address return ReturnCodes.OK; } function employeeMigratesToNewESOP(ESOPMigration migration) external onlyESOPOpen hasEmployee(msg.sender) isCurrentCode returns (ReturnCodes) { // employee may migrate to new ESOP contract with different rules // if migration not set up by company then throw if (address(migration) == 0 || migrations[msg.sender] != migration) throw; // first give back what you already own removeEmployeesWithExpiredSignaturesAndReturnFadeout(); // only employed and terminated users may migrate Employee memory emp = _loademp(msg.sender); if (emp.state != EmployeeState.Employed && emp.state != EmployeeState.Terminated) { return _logerror(ReturnCodes.InvalidEmployeeState); } // with accelerated vesting if possible - take out all possible options var (pool, extra, _) = optionsCalculator.calculateOptionsComponents(serializeEmployee(emp), currentTime(), 0, false); delete migrations[msg.sender]; // execute migration procedure migration.migrate(msg.sender, pool, extra); // extra options are moved to new contract totalExtraOptions -= emp.state == EmployeeState.Employed ? emp.extraOptions : extra; // pool options are moved to new contract and removed from The Pool // please note that separate Pool will manage migrated options and // algorithm that returns to pool and distributes will not be used totalPoolOptions -= emp.state == EmployeeState.Employed ? emp.poolOptions : pool; // gone from current contract employees.removeEmployee(msg.sender); EmployeeMigrated(msg.sender, migration, pool, extra); return ReturnCodes.OK; } function calcEffectiveOptionsForEmployee(address e, uint32 calcAtTime) public constant hasEmployee(e) isCurrentCode returns (uint) { return optionsCalculator.calculateOptions(employees.getSerializedEmployee(e), calcAtTime, conversionOfferedAt, false); } function _logerror(ReturnCodes c) private returns (ReturnCodes) { ReturnCode(c); return c; } function _loademp(address e) private constant returns (Employee memory) { return deserializeEmployee(employees.getSerializedEmployee(e)); } function _saveemp(address e, Employee memory emp) private { employees.setEmployee(e, emp.issueDate, emp.timeToSign, emp.terminatedAt, emp.fadeoutStarts, emp.poolOptions, emp.extraOptions, emp.suspendedAt, emp.state); } function completeCodeUpdate() public onlyOwner inCodeUpdate { employees.transferOwnership(msg.sender); CodeUpdateable.completeCodeUpdate(); } function() payable { throw; } function ESOP(address company, address pRootOfTrust, OptionsCalculator pOptionsCalculator, EmployeesList pEmployeesList) { //esopState = ESOPState.New; // thats initial value companyAddress = company; rootOfTrust = pRootOfTrust; employees = pEmployeesList; optionsCalculator = pOptionsCalculator; } } contract OptionsCalculator is Ownable, Destructable, Math, ESOPTypes { // cliff duration in seconds uint public cliffPeriod; // vesting duration in seconds uint public vestingPeriod; // maximum promille that can fade out uint public maxFadeoutPromille; // minimal options after fadeout function residualAmountPromille() public constant returns(uint) { return FP_SCALE - maxFadeoutPromille; } // exit bonus promille uint public bonusOptionsPromille; // per mille of unassigned poolOptions that new employee gets uint public newEmployeePoolPromille; // options per share uint public optionsPerShare; // options strike price uint constant public STRIKE_PRICE = 1; // company address address public companyAddress; // checks if calculator i initialized function hasParameters() public constant returns(bool) { return optionsPerShare > 0; } modifier onlyCompany() { if (companyAddress != msg.sender) throw; _; } function calcNewEmployeePoolOptions(uint remainingPoolOptions) public constant returns (uint) { return divRound(remainingPoolOptions * newEmployeePoolPromille, FP_SCALE); } function calculateVestedOptions(uint t, uint vestingStarts, uint options) public constant returns (uint) { if (t <= vestingStarts) return 0; // apply vesting uint effectiveTime = t - vestingStarts; // if within cliff nothing is due if (effectiveTime < cliffPeriod) return 0; else return effectiveTime < vestingPeriod ? divRound(options * effectiveTime, vestingPeriod) : options; } function applyFadeoutToOptions(uint32 t, uint32 issueDate, uint32 terminatedAt, uint options, uint vestedOptions) public constant returns (uint) { if (t < terminatedAt) return vestedOptions; uint timefromTermination = t - terminatedAt; // fadeout duration equals to employment duration uint employmentPeriod = terminatedAt - issueDate; // minimum value of options at the end of fadeout, it is a % of all employee's options uint minFadeValue = divRound(options * (FP_SCALE - maxFadeoutPromille), FP_SCALE); // however employee cannot have more than options after fadeout than he was vested at termination if (minFadeValue >= vestedOptions) return vestedOptions; return timefromTermination > employmentPeriod ? minFadeValue : (minFadeValue + divRound((vestedOptions - minFadeValue) * (employmentPeriod - timefromTermination), employmentPeriod)); } function calculateOptionsComponents(uint[9] employee, uint32 calcAtTime, uint32 conversionOfferedAt, bool disableAcceleratedVesting) public constant returns (uint, uint, uint) { // returns tuple of (vested pool options, vested extra options, bonus) Employee memory emp = deserializeEmployee(employee); // no options for converted options or when esop is not singed if (emp.state == EmployeeState.OptionsExercised || emp.state == EmployeeState.WaitingForSignature) return (0,0,0); // no options when esop is being converted and conversion deadline expired bool isESOPConverted = conversionOfferedAt > 0 && calcAtTime >= conversionOfferedAt; // this function time-travels uint issuedOptions = emp.poolOptions + emp.extraOptions; // employee with no options if (issuedOptions == 0) return (0,0,0); // if emp is terminated but we calc options before term, simulate employed again if (calcAtTime < emp.terminatedAt && emp.terminatedAt > 0) emp.state = EmployeeState.Employed; uint vestedOptions = issuedOptions; bool accelerateVesting = isESOPConverted && emp.state == EmployeeState.Employed && !disableAcceleratedVesting; if (!accelerateVesting) { // choose vesting time uint32 calcVestingAt = emp.state == // if terminated then vesting calculated at termination EmployeeState.Terminated ? emp.terminatedAt : // if employee is supended then compute vesting at suspension time (emp.suspendedAt > 0 && emp.suspendedAt < calcAtTime ? emp.suspendedAt : // if conversion offer then vesting calucated at time the offer was made conversionOfferedAt > 0 ? conversionOfferedAt : // otherwise use current time calcAtTime); vestedOptions = calculateVestedOptions(calcVestingAt, emp.issueDate, issuedOptions); } // calc fadeout for terminated employees if (emp.state == EmployeeState.Terminated) { // use conversion event time to compute fadeout to stop fadeout on conversion IF not after conversion date vestedOptions = applyFadeoutToOptions(isESOPConverted ? conversionOfferedAt : calcAtTime, emp.issueDate, emp.terminatedAt, issuedOptions, vestedOptions); } var (vestedPoolOptions, vestedExtraOptions) = extractVestedOptionsComponents(emp.poolOptions, emp.extraOptions, vestedOptions); // if (vestedPoolOptions + vestedExtraOptions != vestedOptions) throw; return (vestedPoolOptions, vestedExtraOptions, accelerateVesting ? divRound(vestedPoolOptions*bonusOptionsPromille, FP_SCALE) : 0 ); } function calculateOptions(uint[9] employee, uint32 calcAtTime, uint32 conversionOfferedAt, bool disableAcceleratedVesting) public constant returns (uint) { var (vestedPoolOptions, vestedExtraOptions, bonus) = calculateOptionsComponents(employee, calcAtTime, conversionOfferedAt, disableAcceleratedVesting); return vestedPoolOptions + vestedExtraOptions + bonus; } function extractVestedOptionsComponents(uint issuedPoolOptions, uint issuedExtraOptions, uint vestedOptions) public constant returns (uint, uint) { // breaks down vested options into pool options and extra options components if (issuedExtraOptions == 0) return (vestedOptions, 0); uint poolOptions = divRound(issuedPoolOptions*vestedOptions, issuedPoolOptions + issuedExtraOptions); return (poolOptions, vestedOptions - poolOptions); } function calculateFadeoutToPool(uint32 t, uint[9] employee) public constant returns (uint, uint) { Employee memory emp = deserializeEmployee(employee); uint vestedOptions = calculateVestedOptions(emp.terminatedAt, emp.issueDate, emp.poolOptions); uint returnedPoolOptions = applyFadeoutToOptions(emp.fadeoutStarts, emp.issueDate, emp.terminatedAt, emp.poolOptions, vestedOptions) - applyFadeoutToOptions(t, emp.issueDate, emp.terminatedAt, emp.poolOptions, vestedOptions); uint vestedExtraOptions = calculateVestedOptions(emp.terminatedAt, emp.issueDate, emp.extraOptions); uint returnedExtraOptions = applyFadeoutToOptions(emp.fadeoutStarts, emp.issueDate, emp.terminatedAt, emp.extraOptions, vestedExtraOptions) - applyFadeoutToOptions(t, emp.issueDate, emp.terminatedAt, emp.extraOptions, vestedExtraOptions); return (returnedPoolOptions, returnedExtraOptions); } function simulateOptions(uint32 issueDate, uint32 terminatedAt, uint32 poolOptions, uint32 extraOptions, uint32 suspendedAt, uint8 employeeState, uint32 calcAtTime) public constant returns (uint) { Employee memory emp = Employee({issueDate: issueDate, terminatedAt: terminatedAt, poolOptions: poolOptions, extraOptions: extraOptions, state: EmployeeState(employeeState), timeToSign: issueDate+2 weeks, fadeoutStarts: terminatedAt, suspendedAt: suspendedAt, idx:1}); return calculateOptions(serializeEmployee(emp), calcAtTime, 0, false); } function setParameters(uint32 pCliffPeriod, uint32 pVestingPeriod, uint32 pResidualAmountPromille, uint32 pBonusOptionsPromille, uint32 pNewEmployeePoolPromille, uint32 pOptionsPerShare) external onlyCompany { if (pResidualAmountPromille > FP_SCALE || pBonusOptionsPromille > FP_SCALE || pNewEmployeePoolPromille > FP_SCALE || pOptionsPerShare == 0) throw; if (pCliffPeriod > pVestingPeriod) throw; // initialization cannot be called for a second time if (hasParameters()) throw; cliffPeriod = pCliffPeriod; vestingPeriod = pVestingPeriod; maxFadeoutPromille = FP_SCALE - pResidualAmountPromille; bonusOptionsPromille = pBonusOptionsPromille; newEmployeePoolPromille = pNewEmployeePoolPromille; optionsPerShare = pOptionsPerShare; } function OptionsCalculator(address pCompanyAddress) { companyAddress = pCompanyAddress; } } contract ProceedsOptionsConverter is Ownable, ERC20OptionsConverter { mapping (address => uint) internal withdrawals; uint[] internal payouts; function makePayout() converted payable onlyOwner public { // it does not make sense to distribute less than ether if (msg.value < 1 ether) throw; payouts.push(msg.value); } function withdraw() converted public returns (uint) { // withdraw for msg.sender uint balance = balanceOf(msg.sender); if (balance == 0) return 0; uint paymentId = withdrawals[msg.sender]; // if all payouts for given token holder executed then exit if (paymentId == payouts.length) return 0; uint payout = 0; for (uint i = paymentId; i<payouts.length; i++) { // it is safe to make payouts pro-rata: (1) token supply will not change - check converted/conversion modifiers // -- (2) balances will not change: check transfer override which limits transfer between accounts // NOTE: safeMul throws on overflow, can lock users out of their withdrawals if balance is very high // @remco I know. any suggestions? expression below gives most precision uint thisPayout = divRound(safeMul(payouts[i], balance), totalSupply); payout += thisPayout; } // change now to prevent re-entry (not necessary due to low send() gas limit) withdrawals[msg.sender] = payouts.length; if (payout > 0) { // now modify payout within 1000 weis as we had rounding errors coming from pro-rata amounts // @remco maximum rounding error is (num_employees * num_payments) / 2 with the mean 0 // --- 1000 wei is still nothing, please explain me what problem you see here if ( absDiff(this.balance, payout) < 1000 wei ) payout = this.balance; // send all //if(!msg.sender.call.value(payout)()) // re entry test // throw; if (!msg.sender.send(payout)) throw; } return payout; } function transfer(address _to, uint _value) public converted { // if anything was withdrawn then block transfer to prevent multiple withdrawals // todo: we could allow transfer to new account (no token balance) // todo: we could allow transfer between account that fully withdrawn (but what's the point? -token has 0 value then) // todo: there are a few other edge cases where there's transfer and no double spending if (withdrawals[_to] > 0 || withdrawals[msg.sender] > 0) throw; ERC20OptionsConverter.transfer(_to, _value); } function ProceedsOptionsConverter(address esop, uint32 exerciseDeadline, uint32 conversionDeadline) ERC20OptionsConverter(esop, exerciseDeadline, conversionDeadline) { } } contract RoT is Ownable { address public ESOPAddress; event ESOPAndCompanySet(address ESOPAddress, address companyAddress); function setESOP(address ESOP, address company) public onlyOwner { // owner sets ESOP and company only once then passes ownership to company // initially owner is a developer/admin ESOPAddress = ESOP; transferOwnership(company); ESOPAndCompanySet(ESOP, company); } function killOnUnsupportedFork() public onlyOwner { // this method may only be called by company on unsupported forks delete ESOPAddress; selfdestruct(owner); } }
will throw on unknown address
function getOldESOP() public constant returns (address); function migrate(address employee, uint poolOptions, uint extraOptions) onlyOldESOP public; } modifier hasEmployee(address e) { if (!employees.hasEmployee(e)) throw; _; }
5,497,839
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./NonReentrancy.sol"; import "./WeekManaged.sol"; import "./interfaces/IAssetManager.sol"; import "./interfaces/IBuyer.sol"; import "./interfaces/IGuarantor.sol"; import "./interfaces/IRegistry.sol"; // This contract is owned by Timelock. contract Guarantor is IGuarantor, Ownable, WeekManaged, NonReentrancy { using SafeERC20 for IERC20; using SafeMath for uint256; IRegistry public registry; struct WithdrawRequest { uint256 amount; uint256 time; bool executed; } // who => week => assetIndex => WithdrawRequest mapping(address => mapping(uint256 => mapping(uint16 => WithdrawRequest))) public withdrawRequestMap; struct PoolInfo { uint256 weekOfPremium; uint256 weekOfBonus; uint256 premiumPerShare; uint256 bonusPerShare; } mapping(uint16 => PoolInfo) public poolInfo; struct UserBalance { uint256 currentBalance; uint256 futureBalance; } mapping(address => mapping(uint16 => UserBalance)) public userBalance; struct UserInfo { uint256 week; uint256 premium; uint256 bonus; } mapping(address => UserInfo) public userInfo; // Balance here not withdrawn yet, and are good for staking bonus. // assetIndex => amount mapping(uint16 => uint256) public assetBalance; struct PayoutInfo { address toAddress; uint256 total; uint256 unitPerShare; uint256 paid; bool finished; } // assetIndex => payoutId => PayoutInfo mapping(uint16 => mapping(uint256 => PayoutInfo)) public payoutInfo; // assetIndex => payoutId mapping(uint16 => uint256) public payoutIdMap; // who => assetIndex => payoutId mapping(address => mapping(uint16 => uint256)) userPayoutIdMap; constructor () public { } function setRegistry(IRegistry registry_) external onlyOwner { registry = registry_; } // Update and pay last week's premium. function updatePremium(uint16 assetIndex_) external lock { uint256 week = getCurrentWeek(); require(IBuyer(registry.buyer()).weekToUpdate() == week, "buyer not ready"); require(poolInfo[assetIndex_].weekOfPremium < week, "already updated"); uint256 amount = IBuyer(registry.buyer()).premiumForGuarantor(assetIndex_); if (assetBalance[assetIndex_] > 0) { IERC20(registry.baseToken()).safeTransferFrom(registry.buyer(), address(this), amount); poolInfo[assetIndex_].premiumPerShare = amount.mul(registry.UNIT_PER_SHARE()).div(assetBalance[assetIndex_]); } poolInfo[assetIndex_].weekOfPremium = week; } // Update and pay last week's bonus. function updateBonus(uint16 assetIndex_, uint256 amount_) external lock override { require(msg.sender == registry.bonus(), "Only Bonus can call"); uint256 week = getCurrentWeek(); require(poolInfo[assetIndex_].weekOfBonus < week, "already updated"); if (assetBalance[assetIndex_] > 0) { IERC20(registry.tidalToken()).safeTransferFrom(msg.sender, address(this), amount_); poolInfo[assetIndex_].bonusPerShare = amount_.mul(registry.UNIT_PER_SHARE()).div(assetBalance[assetIndex_]); } poolInfo[assetIndex_].weekOfBonus = week; } // Called for every user every week. function update(address who_) external { uint256 week = getCurrentWeek(); require(userInfo[who_].week < week, "Already updated"); uint16 index; // Assert if premium or bonus not updated, or user already updated. for (index = 0; index < IAssetManager(registry.assetManager()).getAssetLength(); ++index) { require(poolInfo[index].weekOfPremium == week && poolInfo[index].weekOfBonus == week, "Not ready"); } // For every asset for (index = 0; index < IAssetManager(registry.assetManager()).getAssetLength(); ++index) { uint256 currentBalance = userBalance[who_][index].currentBalance; uint256 futureBalance = userBalance[who_][index].futureBalance; // Update premium. userInfo[who_].premium = userInfo[who_].premium.add(currentBalance.mul( poolInfo[index].premiumPerShare).div(registry.UNIT_PER_SHARE())); // Update bonus. userInfo[who_].bonus = userInfo[who_].bonus.add(currentBalance.mul( poolInfo[index].bonusPerShare).div(registry.UNIT_PER_SHARE())); // Update balances and baskets if no claims. if (!isAssetLocked(who_, index)) { assetBalance[index] = assetBalance[index].add(futureBalance).sub(currentBalance); userBalance[who_][index].currentBalance = futureBalance; } } // Update week. userInfo[who_].week = week; } function isAssetLocked(address who_, uint16 assetIndex_) public view returns(bool) { uint256 payoutId = payoutIdMap[assetIndex_]; return payoutId > 0 && !payoutInfo[assetIndex_][payoutId].finished && userPayoutIdMap[who_][assetIndex_] < payoutId; } function hasPendingPayout(uint16 assetIndex_) public view returns(bool) { uint256 payoutId = payoutIdMap[assetIndex_]; return payoutId > 0 && !payoutInfo[assetIndex_][payoutId].finished; } function deposit(uint16 assetIndex_, uint256 amount_) external lock { require(!hasPendingPayout(assetIndex_), "Has pending payout"); require(userInfo[msg.sender].week == getCurrentWeek(), "Not updated yet"); address token = IAssetManager(registry.assetManager()).getAssetToken(assetIndex_); IERC20(token).safeTransferFrom(msg.sender, address(this), amount_); userBalance[msg.sender][assetIndex_].futureBalance = userBalance[msg.sender][assetIndex_].futureBalance.add(amount_); } function reduceDeposit(uint16 assetIndex_, uint256 amount_) external lock { // Even asset locked, user can still reduce. require(userInfo[msg.sender].week == getCurrentWeek(), "Not updated yet"); require(amount_ <= userBalance[msg.sender][assetIndex_].futureBalance.sub( userBalance[msg.sender][assetIndex_].currentBalance), "Not enough future balance"); address token = IAssetManager(registry.assetManager()).getAssetToken(assetIndex_); IERC20(token).safeTransfer(msg.sender, amount_); userBalance[msg.sender][assetIndex_].futureBalance = userBalance[msg.sender][assetIndex_].futureBalance.sub(amount_); } function withdraw(uint16 assetIndex_, uint256 amount_) external { require(!hasPendingPayout(assetIndex_), "Has pending payout"); require(userInfo[msg.sender].week == getCurrentWeek(), "Not updated yet"); require(amount_ > 0, "Requires positive amount"); require(amount_ <= userBalance[msg.sender][assetIndex_].currentBalance, "Not enough user balance"); WithdrawRequest memory request; request.amount = amount_; request.time = getNow(); request.executed = false; withdrawRequestMap[msg.sender][getUnlockWeek()][assetIndex_] = request; } function withdrawReady(address who_, uint16 assetIndex_) external lock { WithdrawRequest storage request = withdrawRequestMap[who_][getCurrentWeek()][assetIndex_]; require(!hasPendingPayout(assetIndex_), "Has pending payout"); require(userInfo[who_].week == getCurrentWeek(), "Not updated yet"); require(!request.executed, "already executed"); require(request.time > 0, "No request"); uint256 unlockTime = getUnlockTime(request.time); require(getNow() > unlockTime, "Not ready to withdraw yet"); address token = IAssetManager(registry.assetManager()).getAssetToken(assetIndex_); IERC20(token).safeTransfer(who_, request.amount); assetBalance[assetIndex_] = assetBalance[assetIndex_].sub(request.amount); userBalance[who_][assetIndex_].currentBalance = userBalance[who_][assetIndex_].currentBalance.sub(request.amount); userBalance[who_][assetIndex_].futureBalance = userBalance[who_][assetIndex_].futureBalance.sub(request.amount); request.executed = true; } function claimPremium() external lock { IERC20(registry.baseToken()).safeTransfer(msg.sender, userInfo[msg.sender].premium); userInfo[msg.sender].premium = 0; } function claimBonus() external lock { IERC20(registry.tidalToken()).safeTransfer(msg.sender, userInfo[msg.sender].bonus); userInfo[msg.sender].bonus = 0; } function startPayout(uint16 assetIndex_, uint256 payoutId_) external override { require(msg.sender == registry.committee(), "Only commitee can call"); require(payoutId_ == payoutIdMap[assetIndex_] + 1, "payoutId should be increasing"); payoutIdMap[assetIndex_] = payoutId_; } function setPayout(uint16 assetIndex_, uint256 payoutId_, address toAddress_, uint256 total_) external override { require(msg.sender == registry.committee(), "Only commitee can call"); require(payoutId_ == payoutIdMap[assetIndex_], "payoutId should be started"); require(payoutInfo[assetIndex_][payoutId_].toAddress == address(0), "already set"); require(total_ <= assetBalance[assetIndex_], "More than asset"); // total_ can be 0. payoutInfo[assetIndex_][payoutId_].toAddress = toAddress_; payoutInfo[assetIndex_][payoutId_].total = total_; payoutInfo[assetIndex_][payoutId_].unitPerShare = total_.mul(registry.UNIT_PER_SHARE()).div(assetBalance[assetIndex_]); payoutInfo[assetIndex_][payoutId_].paid = 0; payoutInfo[assetIndex_][payoutId_].finished = false; } // This function can be called by anyone. function doPayout(address who_, uint16 assetIndex_) external { uint256 payoutId = payoutIdMap[assetIndex_]; require(payoutInfo[assetIndex_][payoutId].toAddress != address(0), "not set"); require(userPayoutIdMap[who_][assetIndex_] < payoutId, "Already paid"); userPayoutIdMap[who_][assetIndex_] = payoutId; if (payoutInfo[assetIndex_][payoutId].finished) { // In case someone paid for the difference. return; } uint256 amountToPay = userBalance[who_][assetIndex_].currentBalance.mul( payoutInfo[assetIndex_][payoutId].unitPerShare).div(registry.UNIT_PER_SHARE()); userBalance[who_][assetIndex_].currentBalance = userBalance[who_][assetIndex_].currentBalance.sub(amountToPay); userBalance[who_][assetIndex_].futureBalance = userBalance[who_][assetIndex_].futureBalance.sub(amountToPay); assetBalance[assetIndex_] = assetBalance[assetIndex_].sub(amountToPay); payoutInfo[assetIndex_][payoutId].paid = payoutInfo[assetIndex_][payoutId].paid.add(amountToPay); } // This function can be called by anyone as long as he will pay for the difference. function finishPayout(uint16 assetIndex_, uint256 payoutId_) external lock { require(payoutId_ <= payoutIdMap[assetIndex_], "payoutId should be valid"); require(!payoutInfo[assetIndex_][payoutId_].finished, "already finished"); address token = IAssetManager(registry.assetManager()).getAssetToken(assetIndex_); if (payoutInfo[assetIndex_][payoutId_].paid < payoutInfo[assetIndex_][payoutId_].total) { // In case there is still small error. IERC20(token).safeTransferFrom( msg.sender, address(this), payoutInfo[assetIndex_][payoutId_].total.sub(payoutInfo[assetIndex_][payoutId_].paid)); payoutInfo[assetIndex_][payoutId_].paid = payoutInfo[assetIndex_][payoutId_].total; } IERC20(token).safeTransfer(payoutInfo[assetIndex_][payoutId_].toAddress, payoutInfo[assetIndex_][payoutId_].total); payoutInfo[assetIndex_][payoutId_].finished = true; } }
This function can be called by anyone as long as he will pay for the difference. In case there is still small error.
function finishPayout(uint16 assetIndex_, uint256 payoutId_) external lock { require(payoutId_ <= payoutIdMap[assetIndex_], "payoutId should be valid"); require(!payoutInfo[assetIndex_][payoutId_].finished, "already finished"); address token = IAssetManager(registry.assetManager()).getAssetToken(assetIndex_); if (payoutInfo[assetIndex_][payoutId_].paid < payoutInfo[assetIndex_][payoutId_].total) { IERC20(token).safeTransferFrom( msg.sender, address(this), payoutInfo[assetIndex_][payoutId_].total.sub(payoutInfo[assetIndex_][payoutId_].paid)); payoutInfo[assetIndex_][payoutId_].paid = payoutInfo[assetIndex_][payoutId_].total; } IERC20(token).safeTransfer(payoutInfo[assetIndex_][payoutId_].toAddress, payoutInfo[assetIndex_][payoutId_].total); payoutInfo[assetIndex_][payoutId_].finished = true; }
5,451,145
./full_match/3/0xCc42A7E6757FcB9da9eCf109285AF2871E0eeE39/sources/browser/Barn.sol
adds a single Ape to the Barn account the address of the staker tokenId the ID of the Ape to add to the Barn/
function _addApeToBarn(address account, uint256 tokenId) internal whenNotPaused _updateEarnings { barn[tokenId] = Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(block.timestamp) }); totalApeStaked += 1; emit TokenStaked(account, tokenId, block.timestamp); }
8,151,478
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ResellingCredit.sol"; import "./RegenerationCredit.sol"; import "./ReclothesShopRoleManager.sol"; import "./ReclothesShopDataTypes.sol"; /** * @title Public core ReClothes on-chain business logic smart contract. This contract enables Customers to send boxes of second-hand clothes, * buy new clothes, and enable the Dealer to evaluate the boxes and sell saleable (second-hand/upcycled) clothes. * This contract guarantees data consistency across private interaction between Recyclers and Dealer, storing those interactions' * available public output. * @author LINKS Foundation. */ contract ReclothesShop is ReclothesShopRoleManager { /** Events */ event SecondHandBoxSent(uint boxId, string description, CLOTH_TYPE[] clothesTypes, uint[] quantities); event SecondHandBoxEvaluated(uint boxId, uint rscAmount); event SecondHandClothesStored(CLOTH_TYPE clothType, uint quantity); event SaleableClothAdded(uint clothId, uint rscPrice, CLOTH_TYPE clothType, CLOTH_SIZE clothSize, CLOTH_STATUS clothStatus, string description, bytes extClothDataHash); event SaleableClothSold(uint clothId, uint rscPrice); event ConfidentialUpcycledClothOnSale(uint clothId, string confidentialTxHash); event ConfidentialBoxSent(CLOTH_TYPE[] clothesTypes, uint[] quantities, string confidentialTxHash); event ConfidentialTokenTransfer(address sender, address receiver, uint amount, string confidentialTxHash); /** Storage */ ResellingCredit public resellingCreditInstance; RegenerationCredit public regenerationCreditInstance; address public reclothesDealer; /// @dev Associate a price (expressed in RSC tokens) for every possible cloth type. mapping(CLOTH_TYPE => uint) public clothTypeToEvaluationPrice; /// @dev Return the Box associated to its unique numeric identifier; otherwise an empty Box. mapping(uint => Box) public idToBox; /// @dev Return the list of SecondHandClothes associated to a Box; otherwise an empty array. mapping(uint => SecondHandClothes[]) public boxToSecondHandClothes; /// @dev Return the SaleableCloth associated to its unique numeric identifier; otherwise an empty SaleableCloth. mapping(uint => SaleableCloth) public idToSaleableCloth; /// @dev Associate a quantity for every possible cloth type (i.e., the clothes are aggregated by cloth type inside the Dealer inventory). mapping(CLOTH_TYPE => uint) public inventory; /// @dev Return the list of unique identifiers for each Box sent by a Customer; otherwise an empty array. mapping(address => uint[]) public customerToBoxesIds; /// @dev Return the list of unique identifiers for each SaleableClothes purchased by a Customer; otherwise an empty array. mapping(address => uint[]) public customerToPurchasedClothesIds; /// @dev Store every SaleableClothes unique identifier. uint[] private _saleableClothesIds; /** Modifiers */ /// @dev Evaluate true when the provided identifier is greater than zero and it is not used for another Box. modifier isValidBoxId(uint _id) { require(_id > 0, "ZERO-ID"); require(idToBox[_id].id == 0, "ALREADY-USED-ID"); _; } /// @dev Evaluate true when the provided identifier is greater than zero and it is not used for another SaleableCloth. modifier isValidClothId(uint _id) { require(_id > 0, "ZERO-ID"); require(idToSaleableCloth[_id].id == 0, "ALREADY-SALEABLE-CLOTH"); _; } /// @dev Evaluate true when the provided identifier is used for a Box. modifier isBox(uint _boxId) { require(idToBox[_boxId].id == _boxId, "NOT-BOX"); _; } /// @dev Avoid inconsistency between clothes types and quantities arrays. modifier areTypesAndQuantitiesArrayInvalid(CLOTH_TYPE[] calldata _clothesTypes, uint[] calldata _quantities) { require(_clothesTypes.length == _quantities.length && _clothesTypes.length <= 6, "INVALID-ARRAYS"); _; } /** Methods */ /** * @notice Deploy a new instance of ReclothesShop smart contract. * @param _resellingCreditAddress The address of the ResellingCredit smart contract. * @param _regenerationCreditAddress The address of the RegenerationCredit smart contract. */ constructor( address _resellingCreditAddress, address _regenerationCreditAddress ) { // Setup the role for the Reclothes Dealer. _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); reclothesDealer = msg.sender; // Setup ResellingCredit Token smart contract instance. resellingCreditInstance = ResellingCredit(_resellingCreditAddress); // Setup RegenerationCredit Token smart contract instance. regenerationCreditInstance = RegenerationCredit(_regenerationCreditAddress); // Standard pricing list for second-hand clothes evaluation in RSC tokens. clothTypeToEvaluationPrice[CLOTH_TYPE.OTHER] = 2; clothTypeToEvaluationPrice[CLOTH_TYPE.TSHIRT] = 4; clothTypeToEvaluationPrice[CLOTH_TYPE.PANT] = 7; clothTypeToEvaluationPrice[CLOTH_TYPE.JACKET] = 15; clothTypeToEvaluationPrice[CLOTH_TYPE.DRESS] = 8; clothTypeToEvaluationPrice[CLOTH_TYPE.SHIRT] = 10; } /** * @notice Send second-hand clothes Box from a Customer account. * @param _boxId The unique numeric id used for identifying the box. * @param _description A short description of the box content. * @param _clothesTypes The clothes types which are contained in the box. * @param _quantities A quantity for each cloth type contained in the box. */ function sendBoxForEvaluation( uint _boxId, string calldata _description, CLOTH_TYPE[] calldata _clothesTypes, uint[] calldata _quantities ) external onlyCustomer isValidBoxId(_boxId) areTypesAndQuantitiesArrayInvalid(_clothesTypes, _quantities) { Box memory secondHandClothesBox = Box( _boxId, block.timestamp, /// @dev Using "block.timestamp" here is safe because it is not involved in critical time constraints operations. _clothesTypes.length, 0, _description, msg.sender ); // Create the SecondHandClothes array for the box clothes. for (uint i = 0; i < _clothesTypes.length; i++) { require(_quantities[i] > 0, "ZERO-QUANTITY"); boxToSecondHandClothes[_boxId].push( SecondHandClothes(CLOTH_TYPE(_clothesTypes[i]), _quantities[i]) ); } // Storage update. idToBox[_boxId] = secondHandClothesBox; customerToBoxesIds[msg.sender].push(_boxId); // Event emit. emit SecondHandBoxSent(_boxId, _description, _clothesTypes, _quantities); } /** * @notice Evaluate a box of second-hand clothes and remunerate the sender with RSC tokens. * @dev RSC tokens' allowance from Dealer to ReclothesShop must satisfy the evaluation made with the pricing list plus the extra amount. * @param _boxId The unique numeric id used for identifying the box. * @param _extraAmountRSC An additional remuneration in RSC tokens for the box sender. */ function evaluateBox(uint _boxId, uint _extraAmountRSC) external isBox(_boxId) onlyReclothesDealer { require(idToBox[_boxId].evaluationInToken == 0, "ALREADY-EVALUATED"); // Estimation of the amount of RSC tokens to be transferred from the Dealer to the sender of the box. uint rscAmount = _extraAmountRSC; SecondHandClothes[] memory secondHandClothes = boxToSecondHandClothes[_boxId]; for (uint i = 0; i < secondHandClothes.length; i++) { rscAmount += clothTypeToEvaluationPrice[secondHandClothes[i].clothType] * secondHandClothes[i].quantity; } // Dealer inventory update. for (uint i = 0; i < secondHandClothes.length; i++) { inventory[CLOTH_TYPE(secondHandClothes[i].clothType)] += secondHandClothes[i].quantity; emit SecondHandClothesStored(secondHandClothes[i].clothType, secondHandClothes[i].quantity); } // Storage update. idToBox[_boxId].evaluationInToken = rscAmount; // Event emit. emit SecondHandBoxEvaluated(_boxId, rscAmount); // Token transfer from Dealer to box sender (Customer). resellingCreditInstance.transferFrom(reclothesDealer, idToBox[_boxId].sender, rscAmount); } /** * @notice Sell a second-hand cloth in the shop. * @dev Decrease by one the quantity of the chosen cloth type from the Dealer inventory. * @param _clothId The unique numeric id used for identifying the SaleableCloth. * @param _rscPrice The price of the SaleableCloth expressed in RSC tokens. * @param _clothType The type of cloth to sell. * @param _clothSize The size of cloth to sell. * @param _description A short description of the cloth. * @param _extClothDataHash A hash of external information related to the dress to sell (e.g., link to the cloth photo). */ function sellSecondHandCloth( uint _clothId, uint _rscPrice, CLOTH_TYPE _clothType, CLOTH_SIZE _clothSize, string calldata _description, bytes calldata _extClothDataHash ) external { require(inventory[_clothType] > 0, "INVENTORY-ZERO-QUANTITY"); _sellCloth( _clothId, _rscPrice, _clothType, _clothSize, CLOTH_STATUS.SECOND_HAND, _description, _extClothDataHash ); // Storage update. inventory[_clothType] -= 1; } /** * @notice Sell an upcycled cloth in the shop. * @dev Requires the confidential transaction hash relating to the confidential transaction sent by the Dealer for buying the cloth from a Recycler. * @param _clothId The unique numeric id used for identifying the SaleableCloth. * @param _rscPrice The price of the SaleableCloth expressed in RSC tokens. * @param _clothType The type of cloth to sell. * @param _clothSize The size of cloth to sell. * @param _description A short description of the cloth. * @param _extClothDataHash A hash of external information related to the dress to sell (e.g., link to the cloth photo). * @param _confidentialTxHash The hash of the confidential transaction sent by the Dealer for buying the cloth from a Recycler. */ function sellUpcycledCloth( uint _clothId, uint _rscPrice, CLOTH_TYPE _clothType, CLOTH_SIZE _clothSize, string calldata _description, bytes calldata _extClothDataHash, string calldata _confidentialTxHash ) external { _sellCloth( _clothId, _rscPrice, _clothType, _clothSize, CLOTH_STATUS.UPCYCLED, _description, _extClothDataHash ); // Event emit. emit ConfidentialUpcycledClothOnSale(_clothId, _confidentialTxHash); } /** * @notice Buy a cloth from the shop. * @param _clothId The unique numeric id used for identifying the SaleableCloth available in the shop. */ function buyCloth(uint _clothId) external onlyCustomer { require(idToSaleableCloth[_clothId].id == _clothId, "INVALID-CLOTH"); require(idToSaleableCloth[_clothId].buyer == address(0x0), "ALREADY-SOLD"); // Storage update. idToSaleableCloth[_clothId].buyer = msg.sender; customerToPurchasedClothesIds[msg.sender].push(_clothId); // Event emit. emit SaleableClothSold(_clothId, idToSaleableCloth[_clothId].price); // Token transfer from sender (Customer) to Dealer. resellingCreditInstance.transferFrom(msg.sender, reclothesDealer, idToSaleableCloth[_clothId].price); } /** * @notice Decrease the Dealer inventory clothes types quantities for the provided amounts. * @dev Requires the confidential transaction hash relating to the confidential transaction sent by the Dealer to send a box of second-hand clothes to a Recycler. * @param _clothesTypes The types of clothes to sell. * @param _quantities The quantities for each cloth type. * @param _confidentialTxHash The hash of the confidential transaction sent by the Dealer to send a box of second-hand clothes to a Recycler. */ function decreaseStockForConfidentialBox( CLOTH_TYPE[] calldata _clothesTypes, uint[] calldata _quantities, string calldata _confidentialTxHash ) external onlyReclothesDealer areTypesAndQuantitiesArrayInvalid(_clothesTypes, _quantities) { // Dealer inventory update. for (uint i = 0; i < _clothesTypes.length; i++) { require(_quantities[i] > 0, "ZERO-QUANTITY"); inventory[_clothesTypes[i]] -= _quantities[i]; } // Event emit. emit ConfidentialBoxSent(_clothesTypes, _quantities, _confidentialTxHash); } /** * @notice Transfer a RSC token amount from Dealer to Recycler. * @dev Requires the confidential transaction hash relating to the confidential transaction sent by the Dealer for buying the cloth from a Recycler. * @param _recycler The Recycler EOA. * @param _rscAmount The RSC token amount to transfer. * @param _confidentialTxHash The hash of the confidential transaction sent by the Dealer for buying the cloth from a Recycler. */ function transferRSCForConfidentialTx( address _recycler, uint _rscAmount, string calldata _confidentialTxHash ) external isRecycler(_recycler) onlyReclothesDealer { require(_rscAmount > 0, "ZERO-AMOUNT"); // Event emit. emit ConfidentialTokenTransfer(msg.sender, _recycler, _rscAmount, _confidentialTxHash); // Token transfer from Dealer to Recycler. resellingCreditInstance.transferFrom(msg.sender, _recycler, _rscAmount); } /** * @notice Transfer a RSC token amount from Recycler to Dealer. * @dev Requires the confidential transaction hash relating to the confidential transaction sent by the Recycler for evaluating a second-hand clothes box sent by the Dealer. * @param _rgcAmount The RGC token amount to transfer. * @param _confidentialTxHash The hash of the confidential transaction sent by the Recycler for evaluating a second-hand clothes box sent by the Dealer. */ function transferRGCForConfidentialTx( uint _rgcAmount, string calldata _confidentialTxHash ) external onlyRecycler { require(_rgcAmount > 0, "ZERO-AMOUNT"); // Event emit. emit ConfidentialTokenTransfer(msg.sender, reclothesDealer, _rgcAmount, _confidentialTxHash); // Token transfer from Recycler to Dealer. regenerationCreditInstance.transferFrom(msg.sender, reclothesDealer, _rgcAmount); } /** * @notice Sell a cloth in the shop. * @param _clothId The unique numeric id used for identifying the SaleableCloth. * @param _rscPrice The price of the SaleableCloth expressed in RSC tokens. * @param _clothType The type of cloth to sell. * @param _clothSize The size of cloth to sell. * @param _clothStatus The status of cloth to sell. * @param _description A short description of the cloth. * @param _extClothDataHash A hash of external information related to the dress to sell (e.g., link to the cloth photo). */ function _sellCloth( uint _clothId, uint _rscPrice, CLOTH_TYPE _clothType, CLOTH_SIZE _clothSize, CLOTH_STATUS _clothStatus, string calldata _description, bytes calldata _extClothDataHash ) internal isValidClothId(_clothId) onlyReclothesDealer { require(_rscPrice > 0, "INVALID-PRICE"); SaleableCloth memory saleableCloth = SaleableCloth( _clothId, _rscPrice, CLOTH_TYPE(_clothType), _clothSize, _clothStatus, _description, address(0x0), block.timestamp, /// @dev Using "block.timestamp" here is safe because it is not involved in critical time constraints operations. _extClothDataHash ); // Storage update. _saleableClothesIds.push(_clothId); idToSaleableCloth[_clothId] = saleableCloth; // Event emit. emit SaleableClothAdded(_clothId, _rscPrice, _clothType, _clothSize, CLOTH_STATUS.UPCYCLED, _description, _extClothDataHash); } /** * @notice Return the unique identifiers of every SaleableCloth. * @return The list of unique identifiers. */ function getAllSaleableClothesIds() external view returns(uint[] memory){ return _saleableClothesIds; } /** * @notice Return the unique identifiers of every Box sent by the provided Customer. * @return The list of unique identifiers. */ function getAllCustomerBoxesIds(address _customer) external view returns(uint[] memory){ return customerToBoxesIds[_customer]; } /** * @notice Return the unique identifiers of every SaleableCloth purchased by the provided Customer. * @return The list of unique identifiers. */ function getAllPurchasedClothesIds(address _customer) external view returns(uint[] memory){ return customerToPurchasedClothesIds[_customer]; } }
Return the unique identifiers of every SaleableCloth. return The list of unique identifiers./
function getAllSaleableClothesIds() external view returns(uint[] memory){ return _saleableClothesIds; }
12,669,092
pragma solidity ^0.4.24; contract TokenInfo { // Base prices in wei, going off from an Ether value of $500 uint256 public constant PRIVATESALE_BASE_PRICE_IN_WEI = 200000000000000; uint256 public constant PRESALE_BASE_PRICE_IN_WEI = 600000000000000; uint256 public constant ICO_BASE_PRICE_IN_WEI = 800000000000000; uint256 public constant FIRSTSALE_BASE_PRICE_IN_WEI = 200000000000000; // First sale minimum and maximum contribution, going off from an Ether value of $500 uint256 public constant MIN_PURCHASE_OTHERSALES = 80000000000000000; uint256 public constant MIN_PURCHASE = 1000000000000000000; uint256 public constant MAX_PURCHASE = 1000000000000000000000; // Bonus percentages for each respective sale level uint256 public constant PRESALE_PERCENTAGE_1 = 10; uint256 public constant PRESALE_PERCENTAGE_2 = 15; uint256 public constant PRESALE_PERCENTAGE_3 = 20; uint256 public constant PRESALE_PERCENTAGE_4 = 25; uint256 public constant PRESALE_PERCENTAGE_5 = 35; uint256 public constant ICO_PERCENTAGE_1 = 5; uint256 public constant ICO_PERCENTAGE_2 = 10; uint256 public constant ICO_PERCENTAGE_3 = 15; uint256 public constant ICO_PERCENTAGE_4 = 20; uint256 public constant ICO_PERCENTAGE_5 = 25; // Bonus levels in wei for each respective level uint256 public constant PRESALE_LEVEL_1 = 5000000000000000000; uint256 public constant PRESALE_LEVEL_2 = 10000000000000000000; uint256 public constant PRESALE_LEVEL_3 = 15000000000000000000; uint256 public constant PRESALE_LEVEL_4 = 20000000000000000000; uint256 public constant PRESALE_LEVEL_5 = 25000000000000000000; uint256 public constant ICO_LEVEL_1 = 6666666666666666666; uint256 public constant ICO_LEVEL_2 = 13333333333333333333; uint256 public constant ICO_LEVEL_3 = 20000000000000000000; uint256 public constant ICO_LEVEL_4 = 26666666666666666666; uint256 public constant ICO_LEVEL_5 = 33333333333333333333; // Caps for the respective sales, the amount of tokens allocated to the team and the total cap uint256 public constant PRIVATESALE_TOKENCAP = 18750000; uint256 public constant PRESALE_TOKENCAP = 18750000; uint256 public constant ICO_TOKENCAP = 22500000; uint256 public constant FIRSTSALE_TOKENCAP = 5000000; uint256 public constant LEDTEAM_TOKENS = 35000000; uint256 public constant TOTAL_TOKENCAP = 100000000; uint256 public constant DECIMALS_MULTIPLIER = 1 ether; address public constant LED_MULTISIG = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; constructor() public {} /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } contract ApproveAndCallReceiver { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /** * @title Controllable * @dev The Controllable contract has an controller address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Controllable { address public controller; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. */ constructor() public { controller = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyController() { require(msg.sender == controller); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newController The address to transfer ownership to. */ function transferControl(address newController) public onlyController { if (newController != address(0)) { controller = newController; } } } /// @dev The token controller contract must implement these functions contract ControllerInterface { function proxyPayment(address _owner) public payable returns(bool); function onTransfer(address _from, address _to, uint _amount) public returns(bool); function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool); function approve(address _spender, uint256 _amount) public returns (bool); function allowance(address _owner, address _spender) public constant returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Crowdsale is Pausable, TokenInfo { using SafeMath for uint256; LedTokenInterface public ledToken; uint256 public startTime; uint256 public endTime; uint256 public totalWeiRaised; uint256 public tokensMinted; uint256 public totalSupply; uint256 public contributors; uint256 public surplusTokens; bool public finalized; bool public ledTokensAllocated; address public ledMultiSig = LED_MULTISIG; //uint256 public tokenCap = FIRSTSALE_TOKENCAP; //uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; //uint256 public weiCap = tokenCap * FIRSTSALE_BASE_PRICE_IN_WEI; bool public started = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event NewClonedToken(address indexed _cloneToken); event OnTransfer(address _from, address _to, uint _amount); event OnApprove(address _owner, address _spender, uint _amount); event LogInt(string _name, uint256 _value); event Finalized(); // constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { // startTime = _startTime; // endTime = _endTime; // ledToken = LedTokenInterface(_tokenAddress); // assert(_tokenAddress != 0x0); // assert(_startTime > 0); // assert(_endTime > _startTime); // } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ /*function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE && weiAmount <= MAX_PURCHASE); uint256 priceInWei = FIRSTSALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); }*/ /** * Forwards funds to the tokensale wallet */ function forwardFunds() internal { ledMultiSig.transfer(msg.value); } /** * Validates the purchase (period, minimum amount, within cap) * @return {bool} valid */ function validPurchase() internal constant returns (bool) { uint256 current = now; bool presaleStarted = (current >= startTime || started); bool presaleNotEnded = current <= endTime; bool nonZeroPurchase = msg.value != 0; return nonZeroPurchase && presaleStarted && presaleNotEnded; } /** * Returns the total Led token supply * @return totalSupply {uint256} Led Token Total Supply */ function totalSupply() public constant returns (uint256) { return ledToken.totalSupply(); } /** * Returns token holder Led Token balance * @param _owner {address} Token holder address * @return balance {uint256} Corresponding token holder balance */ function balanceOf(address _owner) public constant returns (uint256) { return ledToken.balanceOf(_owner); } /** * Change the Led Token controller * @param _newController {address} New Led Token controller */ function changeController(address _newController) public onlyOwner { require(isContract(_newController)); ledToken.transferControl(_newController); } function enableMasterTransfers() public onlyOwner { ledToken.enableMasterTransfers(true); } function lockMasterTransfers() public onlyOwner { ledToken.enableMasterTransfers(false); } function forceStart() public onlyOwner { started = true; } /*function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; }*/ function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } modifier whenNotFinalized() { require(!finalized); _; } } /** * @title FirstSale * FirstSale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract FirstSale is Crowdsale { uint256 public tokenCap = FIRSTSALE_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * FIRSTSALE_BASE_PRICE_IN_WEI; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE && weiAmount <= MAX_PURCHASE); uint256 priceInWei = FIRSTSALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; } } contract LedToken is Controllable { using SafeMath for uint256; LedTokenInterface public parentToken; TokenFactoryInterface public tokenFactory; string public name; string public symbol; string public version; uint8 public decimals; uint256 public parentSnapShotBlock; uint256 public creationBlock; bool public transfersEnabled; bool public masterTransfersEnabled; address public masterWallet = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; struct Checkpoint { uint128 fromBlock; uint128 value; } Checkpoint[] totalSupplyHistory; mapping(address => Checkpoint[]) balances; mapping (address => mapping (address => uint)) allowed; bool public mintingFinished = false; bool public presaleBalancesLocked = false; uint256 public totalSupplyAtCheckpoint; event MintFinished(); event NewCloneToken(address indexed cloneToken); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); event Transfer(address indexed from, address indexed to, uint256 value); constructor( address _tokenFactory, address _parentToken, uint256 _parentSnapShotBlock, string _tokenName, string _tokenSymbol ) public { tokenFactory = TokenFactoryInterface(_tokenFactory); parentToken = LedTokenInterface(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; name = _tokenName; symbol = _tokenSymbol; decimals = 18; transfersEnabled = false; masterTransfersEnabled = false; creationBlock = block.number; version = '0.1'; } /** * Returns the total Led token supply at the current block * @return total supply {uint256} */ function totalSupply() public constant returns (uint256) { return totalSupplyAt(block.number); } /** * Returns the total Led token supply at the given block number * @param _blockNumber {uint256} * @return total supply {uint256} */ function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0x0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } /** * Returns the token holder balance at the current block * @param _owner {address} * @return balance {uint256} */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /** * Returns the token holder balance the the given block number * @param _owner {address} * @param _blockNumber {uint256} * @return balance {uint256} */ function balanceOfAt(address _owner, uint256 _blockNumber) public constant returns (uint256) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0x0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /** * Standard ERC20 transfer tokens function * @param _to {address} * @param _amount {uint} * @return success {bool} */ function transfer(address _to, uint256 _amount) public returns (bool success) { return doTransfer(msg.sender, _to, _amount); } /** * Standard ERC20 transferFrom function * @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; return doTransfer(_from, _to, _amount); } /** * Standard ERC20 approve function * @param _spender {address} * @param _amount {uint256} * @return success {bool} */ function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * Standard ERC20 approve function * @param _spender {address} * @param _amount {uint256} * @return success {bool} */ function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success) { approve(_spender, _amount); ApproveAndCallReceiver(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /** * Standard ERC20 allowance function * @param _owner {address} * @param _spender {address} * @return remaining {uint256} */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Internal Transfer function - Updates the checkpoint ledger * @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function doTransfer(address _from, address _to, uint256 _amount) internal returns(bool) { if (msg.sender != masterWallet) { require(transfersEnabled); } else { require(masterTransfersEnabled); } require(_amount > 0); require(parentSnapShotBlock < block.number); require((_to != address(0)) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); return true; } /** * Token creation functions - can only be called by the tokensale controller during the tokensale period * @param _owner {address} * @param _amount {uint256} * @return success {bool} */ function mint(address _owner, uint256 _amount) public onlyController canMint returns (bool) { uint256 curTotalSupply = totalSupply(); uint256 previousBalanceTo = balanceOf(_owner); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(0, _owner, _amount); return true; } modifier canMint() { require(!mintingFinished); _; } /** * Import presale balances before the start of the token sale. After importing * balances, lockPresaleBalances() has to be called to prevent further modification * of presale balances. * @param _addresses {address[]} Array of presale addresses * @param _balances {uint256[]} Array of balances corresponding to presale addresses. * @return success {bool} */ function importPresaleBalances(address[] _addresses, uint256[] _balances) public onlyController returns (bool) { require(presaleBalancesLocked == false); for (uint256 i = 0; i < _addresses.length; i++) { totalSupplyAtCheckpoint += _balances[i]; updateValueAtNow(balances[_addresses[i]], _balances[i]); updateValueAtNow(totalSupplyHistory, totalSupplyAtCheckpoint); emit Transfer(0, _addresses[i], _balances[i]); } return true; } /** * Lock presale balances after successful presale balance import * @return A boolean that indicates if the operation was successful. */ function lockPresaleBalances() public onlyController returns (bool) { presaleBalancesLocked = true; return true; } /** * Lock the minting of Led Tokens - to be called after the presale * @return {bool} success */ function finishMinting() public onlyController returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * Enable or block transfers - to be called in case of emergency * @param _value {bool} */ function enableTransfers(bool _value) public onlyController { transfersEnabled = _value; } /** * Enable or block transfers - to be called in case of emergency * @param _value {bool} */ function enableMasterTransfers(bool _value) public onlyController { masterTransfersEnabled = _value; } /** * Internal balance method - gets a certain checkpoint value a a certain _block * @param _checkpoints {Checkpoint[]} List of checkpoints - supply history or balance history * @return value {uint256} Value of _checkpoints at _block */ function getValueAt(Checkpoint[] storage _checkpoints, uint256 _block) constant internal returns (uint256) { if (_checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= _checkpoints[_checkpoints.length-1].fromBlock) return _checkpoints[_checkpoints.length-1].value; if (_block < _checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint256 min = 0; uint256 max = _checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (_checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return _checkpoints[min].value; } /** * Internal update method - updates the checkpoint ledger at the current block * @param _checkpoints {Checkpoint[]} List of checkpoints - supply history or balance history * @return value {uint256} Value to add to the checkpoints ledger */ function updateValueAtNow(Checkpoint[] storage _checkpoints, uint256 _value) internal { if ((_checkpoints.length == 0) || (_checkpoints[_checkpoints.length-1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = _checkpoints[_checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = _checkpoints[_checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } function min(uint256 a, uint256 b) internal pure returns (uint) { return a < b ? a : b; } /** * Clones Led Token at the given snapshot block * @param _snapshotBlock {uint256} * @param _name {string} - The cloned token name * @param _symbol {string} - The cloned token symbol * @return clonedTokenAddress {address} */ function createCloneToken(uint256 _snapshotBlock, string _name, string _symbol) public returns(address) { if (_snapshotBlock == 0) { _snapshotBlock = block.number; } if (_snapshotBlock > block.number) { _snapshotBlock = block.number; } LedToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _name, _symbol ); cloneToken.transferControl(msg.sender); // An event to make the token easy to find on the blockchain emit NewCloneToken(address(cloneToken)); return address(cloneToken); } } /** * @title LedToken (LED) * Standard Mintable ERC20 Token * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract LedTokenInterface is Controllable { bool public transfersEnabled; event Mint(address indexed to, uint256 amount); event MintFinished(); event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); event Transfer(address indexed from, address indexed to, uint256 value); function totalSupply() public constant returns (uint); function totalSupplyAt(uint _blockNumber) public constant returns(uint); function balanceOf(address _owner) public constant returns (uint256 balance); function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint); function transfer(address _to, uint256 _amount) public returns (bool success); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); function approve(address _spender, uint256 _amount) public returns (bool success); function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); function mint(address _owner, uint _amount) public returns (bool); function importPresaleBalances(address[] _addresses, uint256[] _balances, address _presaleAddress) public returns (bool); function lockPresaleBalances() public returns (bool); function finishMinting() public returns (bool); function enableTransfers(bool _value) public; function enableMasterTransfers(bool _value) public; function createCloneToken(uint _snapshotBlock, string _cloneTokenName, string _cloneTokenSymbol) public returns (address); } /** * @title Presale * Presale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract Presale is Crowdsale { uint256 public tokenCap = PRESALE_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * PRESALE_BASE_PRICE_IN_WEI; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); uint256 priceInWei = PRESALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 bonusPercentage = determineBonus(weiAmount); uint256 bonusTokens; uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); if(bonusPercentage>0){ uint256 initialDivided = initialTokens.div(100); bonusTokens = initialDivided.mul(bonusPercentage); } else { bonusTokens = 0; } uint256 tokens = initialTokens.add(bonusTokens); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function determineBonus(uint256 _wei) public view returns (uint256) { if(_wei > PRESALE_LEVEL_1) { if(_wei > PRESALE_LEVEL_2) { if(_wei > PRESALE_LEVEL_3) { if(_wei > PRESALE_LEVEL_4) { if(_wei > PRESALE_LEVEL_5) { return PRESALE_PERCENTAGE_5; } else { return PRESALE_PERCENTAGE_4; } } else { return PRESALE_PERCENTAGE_3; } } else { return PRESALE_PERCENTAGE_2; } } else { return PRESALE_PERCENTAGE_1; } } else { return 0; } } function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256){ return ( PRESALE_LEVEL_1, // Amount of ether needed per bonus level PRESALE_LEVEL_2, PRESALE_LEVEL_3, PRESALE_LEVEL_4, PRESALE_LEVEL_5, PRESALE_PERCENTAGE_1, // Bonus percentage per bonus level PRESALE_PERCENTAGE_2, PRESALE_PERCENTAGE_3, PRESALE_PERCENTAGE_4, PRESALE_PERCENTAGE_5 ); } } /** * @title PrivateSale * PrivateSale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract PrivateSale is Crowdsale { uint256 public tokenCap = PRIVATESALE_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * PRIVATESALE_BASE_PRICE_IN_WEI; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); uint256 priceInWei = PRIVATESALE_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function finalize() public onlyOwner { require(paused); require(!finalized); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.transferControl(owner); emit Finalized(); finalized = true; } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract TokenFactory { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, string _tokenSymbol ) public returns (LedToken) { LedToken newToken = new LedToken( this, _parentToken, _snapshotBlock, _tokenName, _tokenSymbol ); newToken.transferControl(msg.sender); return newToken; } } contract TokenFactoryInterface { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, string _tokenSymbol ) public returns (LedToken newToken); } /** * @title Tokensale * Tokensale allows investors to make token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. */ contract TokenSale is Crowdsale { uint256 public tokenCap = ICO_TOKENCAP; uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; uint256 public weiCap = tokenCap * ICO_BASE_PRICE_IN_WEI; uint256 public allocatedTokens; constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { startTime = _startTime; endTime = _endTime; ledToken = LedTokenInterface(_tokenAddress); assert(_tokenAddress != 0x0); assert(_startTime > 0); assert(_endTime > _startTime); } /** * High level token purchase function */ function() public payable { buyTokens(msg.sender); } /** * Low level token purchase function * @param _beneficiary will receive the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { require(_beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); uint256 priceInWei = ICO_BASE_PRICE_IN_WEI; totalWeiRaised = totalWeiRaised.add(weiAmount); uint256 bonusPercentage = determineBonus(weiAmount); uint256 bonusTokens; uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); if(bonusPercentage>0){ uint256 initialDivided = initialTokens.div(100); bonusTokens = initialDivided.mul(bonusPercentage); } else { bonusTokens = 0; } uint256 tokens = initialTokens.add(bonusTokens); tokensMinted = tokensMinted.add(tokens); require(tokensMinted < cap); contributors = contributors.add(1); ledToken.mint(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); forwardFunds(); } function determineBonus(uint256 _wei) public view returns (uint256) { if(_wei > ICO_LEVEL_1) { if(_wei > ICO_LEVEL_2) { if(_wei > ICO_LEVEL_3) { if(_wei > ICO_LEVEL_4) { if(_wei > ICO_LEVEL_5) { return ICO_PERCENTAGE_5; } else { return ICO_PERCENTAGE_4; } } else { return ICO_PERCENTAGE_3; } } else { return ICO_PERCENTAGE_2; } } else { return ICO_PERCENTAGE_1; } } else { return 0; } } function allocateLedTokens() public onlyOwner whenNotFinalized { require(!ledTokensAllocated); allocatedTokens = LEDTEAM_TOKENS.mul(DECIMALS_MULTIPLIER); ledToken.mint(ledMultiSig, allocatedTokens); ledTokensAllocated = true; } function finalize() public onlyOwner { require(paused); require(ledTokensAllocated); surplusTokens = cap - tokensMinted; ledToken.mint(ledMultiSig, surplusTokens); ledToken.finishMinting(); ledToken.enableTransfers(true); emit Finalized(); finalized = true; } function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, bool, uint256, uint256){ uint256 decimals = 18; string memory symbol = "LED"; bool transfersEnabled = ledToken.transfersEnabled(); return ( TOTAL_TOKENCAP, // Tokencap with the decimal point in place. should be 100.000.000 decimals, // Decimals symbol, transfersEnabled, contributors, totalWeiRaised, tokenCap, // Tokencap for the first sale with the decimal point in place. started, startTime, // Start time and end time in Unix timestamp format with a length of 10 numbers. endTime ); } function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256){ return ( ICO_LEVEL_1, // Amount of ether needed per bonus level ICO_LEVEL_2, ICO_LEVEL_3, ICO_LEVEL_4, ICO_LEVEL_5, ICO_PERCENTAGE_1, // Bonus percentage per bonus level ICO_PERCENTAGE_2, ICO_PERCENTAGE_3, ICO_PERCENTAGE_4, ICO_PERCENTAGE_5 ); } }
Internal update method - updates the checkpoint ledger at the current block _checkpoints {Checkpoint[]} List of checkpoints - supply history or balance history return value {uint256} Value to add to the checkpoints ledger/
function updateValueAtNow(Checkpoint[] storage _checkpoints, uint256 _value) internal { if ((_checkpoints.length == 0) || (_checkpoints[_checkpoints.length-1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = _checkpoints[_checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); Checkpoint storage oldCheckPoint = _checkpoints[_checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } }
611,087
pragma solidity ^0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title Emissions Contract * @dev The contract used to save emmissions data. */ contract Emissions { using SafeMath for uint256; struct Emission { uint256 timestamp; uint256 tons; uint256[] arbitrations; bytes32 description; } Emission[] private emissions; uint256 totalEmissions; /** * @dev Constructor */ constructor() public { totalEmissions = 0; } /** * @dev Upload information about emissions * @return An uint256 with the emission id */ function upload( uint256 _tons, uint256[] memory _arbitrations, bytes32 _description) public returns(uint256) { emissions.push(Emission( block.timestamp, _tons, _arbitrations, _description )); totalEmissions = totalEmissions.add(1); return totalEmissions; } /** * @dev Gets all the comapnies. * @return The total amount of emissions by all copanies. */ function getTotal() public view returns (uint256) { return totalEmissions; } /** * @dev Get emission information * @return All the emission information */ function get(uint256 _index) public view returns(uint256, uint256, uint256, bytes32) { return( emissions[_index].timestamp, emissions[_index].tons, emissions[_index].arbitrations.length, emissions[_index].description ); } function getArbitration(uint256 _indexEmission, uint256 _indexArbitration) public view returns(uint256) { return (emissions[_indexEmission].arbitrations[_indexArbitration]); } }
Upload information about emissions return An uint256 with the emission id/
function upload( uint256 _tons, uint256[] memory _arbitrations, bytes32 _description) public returns(uint256) { emissions.push(Emission( block.timestamp, _tons, _arbitrations, _description )); totalEmissions = totalEmissions.add(1); return totalEmissions; }
5,407,435
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import "@solv/v2-solidity-utils/contracts/access/AdminControl.sol"; import "@solv/v2-solidity-utils/contracts/misc/Constants.sol"; import "@solv/v2-solidity-utils/contracts/openzeppelin/utils/ReentrancyGuardUpgradeable.sol"; import "@solv/v2-solidity-utils/contracts/openzeppelin/utils/EnumerableSetUpgradeable.sol"; import "@solv/v2-solidity-utils/contracts/openzeppelin/math/SafeMathUpgradeable.sol"; import "@solv/v2-solidity-utils/contracts/helpers/ERC20TransferHelper.sol"; import "@solv/v2-solidity-utils/contracts/helpers/VNFTTransferHelper.sol"; import "@solv/v2-vnft-core/contracts/interface/optional/IUnderlyingContainer.sol"; import "@solv/v2-solidity-utils/contracts/openzeppelin/token/ERC20/ERC20Upgradeable.sol"; import "./interface/IConvertiblePool.sol"; import "./interface/IPriceOracleManager.sol"; import "./interface/external/IICToken.sol"; import "hardhat/console.sol"; contract ConvertiblePool is IConvertiblePool, AdminControl, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; mapping(uint256 => SlotDetail) internal _slotDetails; mapping(address => EnumerableSetUpgradeable.UintSet) internal _issuerSlots; mapping(address => bool) public fundCurrencies; /// @notice slot => currency => balance mapping(uint256 => mapping(address => uint256)) public slotBalances; IPriceOracleManager public oracle; address public underlyingVestingVoucher; address public underlyingToken; uint8 public priceDecimals; uint8 public valueDecimals; address public voucher; modifier onlyVoucher() { require(_msgSender() == voucher, "only voucher"); _; } function initialize( address underlyingToken_, address oracle_, uint8 priceDecimals_, uint8 valueDecimals_ ) external initializer { AdminControl.__AdminControl_init(_msgSender()); oracle = IPriceOracleManager(oracle_); underlyingToken = underlyingToken_; priceDecimals = priceDecimals_; valueDecimals = valueDecimals_; } function createSlot( address issuer_, address fundCurrency_, uint128 lowestPrice_, uint128 highestPrice_, uint64 effectiveTime_, uint64 maturity_, uint8 collateralType_ ) external onlyVoucher returns (uint256 slot) { validateSlotParams( issuer_, fundCurrency_, lowestPrice_, highestPrice_, effectiveTime_, maturity_, collateralType_ ); slot = getSlot( issuer_, fundCurrency_, lowestPrice_, highestPrice_, effectiveTime_, maturity_, collateralType_ ); require(!_slotDetails[slot].isValid, "slot already existed"); SlotDetail storage slotDetail = _slotDetails[slot]; slotDetail.issuer = issuer_; slotDetail.fundCurrency = fundCurrency_; slotDetail.lowestPrice = lowestPrice_; slotDetail.highestPrice = highestPrice_; slotDetail.effectiveTime = effectiveTime_; slotDetail.maturity = maturity_; slotDetail.collateralType = CollateralType(collateralType_); slotDetail.isValid = true; _issuerSlots[issuer_].add(slot); emit CreateSlot( slot, issuer_, fundCurrency_, lowestPrice_, highestPrice_, effectiveTime_, maturity_, CollateralType(collateralType_) ); } function validateSlotParams( address issuer_, address fundCurrency_, uint128 lowestPrice_, uint128 highestPrice_, uint64 effectiveTime_, uint64 maturity_, uint8 collateralType_ ) public view { require(issuer_ != address(0), "issuer cannot be 0 address"); require(fundCurrencies[fundCurrency_], "unsupported fund currency"); require(collateralType_ < 2, "invalid collateral type"); require( lowestPrice_ > 0 && lowestPrice_ < highestPrice_, "invalid price bounds" ); require( effectiveTime_ > 0 && effectiveTime_ < maturity_, "invalid time setting" ); } function mintWithUnderlyingToken( address minter_, uint256 slot_, uint256 tokenInAmount_ ) external override nonReentrant onlyVoucher returns (uint256 totalValue) { require(minter_ != address(0), "minter cannot be 0 address"); require(tokenInAmount_ != 0, "tokenInAmount cannot be 0"); SlotDetail storage slotDetail = _slotDetails[slot_]; require(slotDetail.isValid, "invalid slot"); require( !slotDetail.isIssuerRefunded && block.timestamp < slotDetail.maturity, "non-mintable slot" ); totalValue = tokenInAmount_.mul(slotDetail.lowestPrice); slotDetail.totalValue = slotDetail.totalValue.add(totalValue); slotBalances[slot_][underlyingToken] = slotBalances[slot_][ underlyingToken ].add(tokenInAmount_); ERC20TransferHelper.doTransferIn( underlyingToken, minter_, tokenInAmount_ ); emit Mint(minter_, slot_, totalValue); } /** * @dev Allow issuers to refund convertible vouchers with fund currency. * Refunding is only allowed before the first holder claiming. Once refunded, * holders will claim in terms of */ function refund(uint256 slot_) external override nonReentrant { require(_issuerSlots[_msgSender()].contains(slot_), "only issuer"); SlotDetail storage slotDetail = _slotDetails[slot_]; require(slotDetail.isValid, "invalid slot"); require(!slotDetail.isIssuerRefunded, "already refunded"); require(slotDetail.settlePrice == 0, "already settled"); slotDetail.isIssuerRefunded = true; // Calculation of currencyAmount only supports ERC20 stable coins (USDT/USDC/DAI/...) uint8 currencyDecimals = ERC20Upgradeable(slotDetail.fundCurrency) .decimals(); uint256 currencyAmount = slotDetail .totalValue .mul(10**currencyDecimals) .div(10**valueDecimals); slotBalances[slot_][slotDetail.fundCurrency] = slotBalances[slot_][ slotDetail.fundCurrency ].add(currencyAmount); ERC20TransferHelper.doTransferIn( slotDetail.fundCurrency, _msgSender(), currencyAmount ); emit Refund(slot_, _msgSender(), currencyAmount); } function getWithdrawableAmount(uint256 slot_) public view returns (uint256 withdrawCurrencyAmount, uint256 withdrawTokenAmount) { SlotDetail storage slotDetail = _slotDetails[slot_]; if ( block.timestamp >= slotDetail.maturity && !slotDetail.isIssuerWithdrawn ) { uint128 settlePrice = slotDetail.settlePrice; if (settlePrice == 0) { settlePrice = getSettlePrice(slot_); if (settlePrice == 0) { return (0, 0); } } if (slotDetail.isIssuerRefunded && settlePrice > slotDetail.highestPrice) { // Calculation of currencyAmount only supports ERC20 stable coins (USDT/USDC/DAI/...) uint8 currencyDecimals = ERC20Upgradeable( slotDetail.fundCurrency ).decimals(); uint256 reservedCurrencyAmount = slotBalances[slot_][ slotDetail.fundCurrency ]; withdrawCurrencyAmount = slotDetail .totalValue .mul(10**currencyDecimals) .div(10**valueDecimals); if (withdrawCurrencyAmount > reservedCurrencyAmount) { withdrawCurrencyAmount = reservedCurrencyAmount; } } if (slotDetail.isIssuerRefunded && settlePrice <= slotDetail.highestPrice) { withdrawTokenAmount = slotDetail.totalValue.div(slotDetail.lowestPrice); } else if (settlePrice > slotDetail.lowestPrice) { if (settlePrice > slotDetail.highestPrice) { settlePrice = slotDetail.highestPrice; } withdrawTokenAmount = slotDetail .totalValue .div(slotDetail.lowestPrice) .sub(slotDetail.totalValue.div(settlePrice)); } uint256 reservedTokenAmount = slotBalances[slot_][underlyingToken]; if (withdrawTokenAmount > reservedTokenAmount) { withdrawTokenAmount = reservedTokenAmount; } } } /** * @notice Allow issuers to withdraw fund currency (if refunded) and remaining underlying token after maturity. */ function withdraw(uint256 slot_) external override nonReentrant returns (uint256 withdrawCurrencyAmount, uint256 withdrawTokenAmount) { require(_issuerSlots[_msgSender()].contains(slot_), "only issuer"); SlotDetail storage slotDetail = _slotDetails[slot_]; require(!slotDetail.isIssuerWithdrawn, "already withdrawn"); uint128 settlePrice = slotDetail.settlePrice; if (settlePrice == 0) { settleConvertiblePrice(slot_); settlePrice = slotDetail.settlePrice; if (settlePrice == 0) { revert("price not settled"); } } (withdrawCurrencyAmount, withdrawTokenAmount) = getWithdrawableAmount( slot_ ); slotDetail.isIssuerWithdrawn = true; if (withdrawCurrencyAmount > 0) { slotBalances[slot_][slotDetail.fundCurrency] = slotBalances[slot_][ slotDetail.fundCurrency ].sub(withdrawCurrencyAmount); ERC20TransferHelper.doTransferOut( slotDetail.fundCurrency, _msgSender(), withdrawCurrencyAmount ); } if (withdrawTokenAmount > 0) { slotBalances[slot_][underlyingToken] = slotBalances[slot_][ underlyingToken ].sub(withdrawTokenAmount); ERC20TransferHelper.doTransferOut( underlyingToken, _msgSender(), withdrawTokenAmount ); } emit Withdraw( slot_, _msgSender(), withdrawCurrencyAmount, withdrawTokenAmount ); } /** * @notice Allow CV holders to claim fund currency or underlying token after maturity. */ function claim( uint256 slot_, address to_, uint256 claimValue_ ) external override onlyVoucher nonReentrant returns (uint256 claimCurrencyAmount, uint256 claimTokenAmount) { SlotDetail storage slotDetail = _slotDetails[slot_]; require(slotDetail.isValid, "invalid slot"); uint128 settlePrice = slotDetail.settlePrice; if (settlePrice == 0) { settleConvertiblePrice(slot_); settlePrice = slotDetail.settlePrice; if (settlePrice == 0) { revert("price not settled"); } } if (!slotDetail.isClaimed) { slotDetail.isClaimed = true; } if ( settlePrice <= slotDetail.highestPrice && slotDetail.isIssuerRefunded ) { uint256 reservedCurrencyAmount = slotBalances[slot_][ slotDetail.fundCurrency ]; claimCurrencyAmount = claimValue_ .mul(10 ** ERC20Upgradeable(slotDetail.fundCurrency).decimals()) .div(10 ** valueDecimals); if (claimCurrencyAmount > reservedCurrencyAmount) { claimCurrencyAmount = reservedCurrencyAmount; } slotBalances[slot_][ slotDetail.fundCurrency ] = reservedCurrencyAmount.sub(claimCurrencyAmount); ERC20TransferHelper.doTransferOut( slotDetail.fundCurrency, payable(to_), claimCurrencyAmount ); } else { if (settlePrice < slotDetail.lowestPrice) { settlePrice = slotDetail.lowestPrice; } else if (settlePrice > slotDetail.highestPrice) { settlePrice = slotDetail.highestPrice; } uint256 reservedTokenAmount = slotBalances[slot_][underlyingToken]; claimTokenAmount = claimValue_.div(settlePrice); if (claimTokenAmount > reservedTokenAmount) { claimTokenAmount = reservedTokenAmount; } slotBalances[slot_][underlyingToken] = reservedTokenAmount.sub( claimTokenAmount ); ERC20TransferHelper.doTransferOut( underlyingToken, payable(to_), claimTokenAmount ); } } function settleConvertiblePrice(uint256 slot_) public override { SlotDetail storage slotDetail = _slotDetails[slot_]; uint128 price = getSettlePrice(slot_); if (price > 0) { slotDetail.settlePrice = price; emit SettlePrice(slot_, slotDetail.settlePrice); } } function getSettlePrice(uint256 slot_) public view override returns (uint128) { SlotDetail storage slotDetail = _slotDetails[slot_]; require(block.timestamp >= slotDetail.maturity, "premature"); int256 iPrice = oracle.getPriceOfMaturity( voucher, slotDetail.maturity ); if (iPrice < 0) { revert("negative price"); } return uint128(iPrice); } function getSlot( address issuer_, address fundCurrency_, uint128 lowestPrice_, uint128 highestPrice_, uint64 effectiveTime_, uint64 maturity_, uint8 collateralType_ ) public view returns (uint256) { return uint256( keccak256( abi.encode( underlyingToken, underlyingVestingVoucher, issuer_, fundCurrency_, lowestPrice_, highestPrice_, effectiveTime_, maturity_, collateralType_ ) ) ); } function getSlotDetail(uint256 slot_) external view returns (SlotDetail memory) { return _slotDetails[slot_]; } function getIssuerSlots(address issuer_) external view returns (uint256[] memory slots) { slots = new uint256[](_issuerSlots[issuer_].length()); for (uint256 i = 0; i < slots.length; i++) { slots[i] = _issuerSlots[issuer_].at(i); } } function getIssuerSlotDetails(address issuer_) external view returns (SlotDetail[] memory slotDetails) { slotDetails = new SlotDetail[](_issuerSlots[issuer_].length()); for (uint256 i = 0; i < slotDetails.length; i++) { slotDetails[i] = _slotDetails[_issuerSlots[issuer_].at(i)]; } } function setUnderlyingVestingVoucher(address underlyingVestingVoucher_) external onlyAdmin { underlyingVestingVoucher = underlyingVestingVoucher_; } function setFundCurrency(address fundCurrency_, bool enable_) external onlyAdmin { fundCurrencies[fundCurrency_] = enable_; emit SetFundCurrency(fundCurrency_, enable_); } function setVoucher(address newVoucher_) external onlyAdmin { require(newVoucher_ != address(0), "new voucher cannot be 0 address"); emit NewVoucher(voucher, newVoucher_); voucher = newVoucher_; } }
Allow issuers to refund convertible vouchers with fund currency. Refunding is only allowed before the first holder claiming. Once refunded, holders will claim in terms of/ Calculation of currencyAmount only supports ERC20 stable coins (USDT/USDC/DAI/...)
function refund(uint256 slot_) external override nonReentrant { require(_issuerSlots[_msgSender()].contains(slot_), "only issuer"); SlotDetail storage slotDetail = _slotDetails[slot_]; require(slotDetail.isValid, "invalid slot"); require(!slotDetail.isIssuerRefunded, "already refunded"); require(slotDetail.settlePrice == 0, "already settled"); slotDetail.isIssuerRefunded = true; uint8 currencyDecimals = ERC20Upgradeable(slotDetail.fundCurrency) .decimals(); uint256 currencyAmount = slotDetail .totalValue .mul(10**currencyDecimals) .div(10**valueDecimals); slotBalances[slot_][slotDetail.fundCurrency] = slotBalances[slot_][ slotDetail.fundCurrency ].add(currencyAmount); ERC20TransferHelper.doTransferIn( slotDetail.fundCurrency, _msgSender(), currencyAmount ); emit Refund(slot_, _msgSender(), currencyAmount); }
6,435,259
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * * Metaverse Travel Agency * ======================= * https://themta.io * twiter: @themtaofficial * * MetaHelmet * ---------- */ /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @dev Implementation of the {IERC165} interface. * * Contracts 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; } } /** * @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); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev 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); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @dev 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; string private baseURI = ""; // 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 baseURI; } function _setBaseURI(string memory baseURI_) internal { baseURI = baseURI_; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @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); } /** * @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(); } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } contract Metahelmet is ERC721Enumerable, Ownable { using SafeMath for uint256; string public METAHELMET_PROVENANCE = ""; uint256 public constant PRICE = 101010000000000000; uint256 public constant MAX_METAHELMETS = 10101; uint256 public constant MAX_PURCHASE = 7; bool public saleIsActive = false; mapping (address => uint256) public whitelistMinted; address public WHITELIST_SIGNER; event Merge(uint256 indexed tokenId, address indexed nftContract, uint256 indexed nftId); event Unmerge(uint256 indexed tokenId); constructor() ERC721("MetaHelmet", "MTAH") {} function withdraw() public onlyOwner { address payable sender = payable(_msgSender()); uint balance = address(this).balance; sender.transfer(balance); } function toggleSale() public onlyOwner { saleIsActive = !saleIsActive; } function setWhiteListSigner(address signer) public onlyOwner { WHITELIST_SIGNER = signer; } /** * Set some Metahelmets aside */ function reserveMetahelmets() public onlyOwner { require(saleIsActive == false, "Impossible reserve a Metahelmet when sale is active"); uint supply = totalSupply(); for (uint i = 0; i < 21; i++) { _safeMint(_msgSender(), supply + i); } } /** * Mint Metahelmet */ function mintMetahelmet(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Metahelmet"); require(numberOfTokens <= MAX_PURCHASE, "Can only mint 7 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_METAHELMETS, "Purchase would exceed max supply of Metahelmets"); require(PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_METAHELMETS) { _safeMint(_msgSender(), mintIndex); } } } /** * PreMint: Only people in whitelist can mint */ function preMintMetahelmet(uint256 numberOfTokens, uint max, bytes memory signature) public payable { bytes32 hash; require(WHITELIST_SIGNER != address(0), "Pre-Mint is not available yet"); require(saleIsActive == false, "Impossible Pre-Mint a Matahelmet when sale is active"); require(numberOfTokens <= MAX_PURCHASE, "Can only mint 7 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_METAHELMETS, "Purchase would exceed max supply of Metahelmets"); require(PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); /* * keccak256(address,number); */ hash = keccak256(abi.encodePacked(_msgSender(), max)); /* * Check Signature */ require(recover(hash,signature) == WHITELIST_SIGNER, "Invalid Signature"); /* * Check max min reached */ require(whitelistMinted[_msgSender()].add(numberOfTokens) <= max, "Max mint reached"); /* * Update total minted in preMint state */ whitelistMinted[_msgSender()] = whitelistMinted[_msgSender()].add(numberOfTokens); uint supply = totalSupply(); for(uint i = 0; i < numberOfTokens; i++) { _safeMint(_msgSender(), supply+i); } } /** * Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { METAHELMET_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function merge(uint256 _tokenId, IERC721 _nftContract, uint256 _nftId) public { require(ownerOf(_tokenId) == _msgSender(), "Only owner can merge tokens"); require(_nftContract.ownerOf(_nftId) == _msgSender(), "Only owner can merge tokens"); emit Merge(_tokenId, address(_nftContract), _nftId); } function unmerge(uint256 _tokenId) public { require(ownerOf(_tokenId) == _msgSender(), "Only owner can unmerge tokens"); emit Unmerge(_tokenId); } function recover(bytes32 _hash, bytes memory _signed) internal pure returns(address) { bytes32 r; bytes32 s; uint8 v; assembly { r:= mload(add(_signed,32)) s:= mload(add(_signed,64)) v:= and(mload(add(_signed,65)) ,255) } return ecrecover(_hash,v,r,s); } }
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())) : ""; }
5,832,131
./partial_match/1/0x67c5F13c56aEb40fd9a937214E5429dAf8A0CfC9/sources/contracts/FCNVault.sol
Mint a given amount of shares (vault tokens) shares is the number of shares/
function mint(uint256 shares) external onlyOwner returns (uint256) { return mint(shares, msg.sender); }
15,753,105
./partial_match/5/0x6626802a931df0CaE056158D06de3979395cE76d/sources/DeporRPOSValidatorController.sol
exit supportvID must be availabledo transfer DPO
function supporterExitValidator(uint256 vID) external { require( validatorData.isVIDAvailable(vID), "validator id is not available" ); require( validatorData.isAddrSupporterOfValidator(msg.sender, vID), "validator is unexcepted " ); dpoContract.transfer( msg.sender, validatorData.queryJoinValidatorRequireDPOAmount() ); validatorData.supporterExitValidator(msg.sender, vID); }
16,858,915
pragma solidity 0.5.17; import '@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol'; import './MixinSignatures.sol'; import './MixinKeys.sol'; import './MixinLockCore.sol'; import './MixinLockManagerRole.sol'; import './MixinFunds.sol'; contract MixinRefunds is MixinLockManagerRole, MixinSignatures, MixinFunds, MixinLockCore, MixinKeys { using SafeMath for uint; // CancelAndRefund will return funds based on time remaining minus this penalty. // This is calculated as `proRatedRefund * refundPenaltyBasisPoints / BASIS_POINTS_DEN`. uint public refundPenaltyBasisPoints; uint public freeTrialLength; /// @notice The typehash per the EIP-712 standard /// @dev This can be computed in JS instead of read from the contract bytes32 private constant CANCEL_TYPEHASH = keccak256('cancelAndRefundFor(address _keyOwner)'); event CancelKey( uint indexed tokenId, address indexed owner, address indexed sendTo, uint refund ); event RefundPenaltyChanged( uint freeTrialLength, uint refundPenaltyBasisPoints ); function _initializeMixinRefunds() internal { // default to 10% refundPenaltyBasisPoints = 1000; } /** * @dev Invoked by the lock owner to destroy the user's ket and perform a refund and cancellation * of the key */ function expireAndRefundFor( address _keyOwner, uint amount ) external onlyLockManager hasValidKey(_keyOwner) { _cancelAndRefund(_keyOwner, amount); } /** * @dev Destroys the key and sends a refund based on the amount of time remaining. * @param _tokenId The id of the key to cancel. */ function cancelAndRefund(uint _tokenId) external onlyKeyManagerOrApproved(_tokenId) { address keyOwner = ownerOf(_tokenId); uint refund = _getCancelAndRefundValue(keyOwner); _cancelAndRefund(keyOwner, refund); } /** * @dev Cancels a key managed by a different user and sends the funds to the msg.sender. * @param _keyManager the key managed by this user will be canceled * @param _v _r _s getCancelAndRefundApprovalHash signed by the _keyOwner * @param _tokenId The key to cancel */ function cancelAndRefundFor( address _keyManager, uint8 _v, bytes32 _r, bytes32 _s, uint _tokenId ) external consumeOffchainApproval( getCancelAndRefundApprovalHash(_keyManager, msg.sender), _keyManager, _v, _r, _s ) { address keyOwner = ownerOf(_tokenId); uint refund = _getCancelAndRefundValue(keyOwner); _cancelAndRefund(keyOwner, refund); } /** * Allow the owner to change the refund penalty. */ function updateRefundPenalty( uint _freeTrialLength, uint _refundPenaltyBasisPoints ) external onlyLockManager { emit RefundPenaltyChanged( _freeTrialLength, _refundPenaltyBasisPoints ); freeTrialLength = _freeTrialLength; refundPenaltyBasisPoints = _refundPenaltyBasisPoints; } /** * @dev Determines how much of a refund a key owner would receive if they issued * a cancelAndRefund block.timestamp. * Note that due to the time required to mine a tx, the actual refund amount will be lower * than what the user reads from this call. */ function getCancelAndRefundValueFor( address _keyOwner ) external view returns (uint refund) { return _getCancelAndRefundValue(_keyOwner); } /** * @notice returns the hash to sign in order to allow another user to cancel on your behalf. * @dev this can be computed in JS instead of read from the contract. * @param _keyManager The key manager's address (also the message signer) * @param _txSender The address cancelling cancel on behalf of the keyOwner * @return approvalHash The hash to sign */ function getCancelAndRefundApprovalHash( address _keyManager, address _txSender ) public view returns (bytes32 approvalHash) { return keccak256( abi.encodePacked( // Approval is specific to this Lock address(this), // The specific function the signer is approving CANCEL_TYPEHASH, // Approval enables only one cancel call keyManagerToNonce[_keyManager], // Approval allows only one account to broadcast the tx _txSender ) ); } /** * @dev cancels the key for the given keyOwner and sends the refund to the msg.sender. */ function _cancelAndRefund( address _keyOwner, uint refund ) internal { Key storage key = keyByOwner[_keyOwner]; emit CancelKey(key.tokenId, _keyOwner, msg.sender, refund); // expirationTimestamp is a proxy for hasKey, setting this to `block.timestamp` instead // of 0 so that we can still differentiate hasKey from hasValidKey. key.expirationTimestamp = block.timestamp; if (refund > 0) { // Security: doing this last to avoid re-entrancy concerns _transfer(tokenAddress, _keyOwner, refund); } // inform the hook if there is one registered if(address(onKeyCancelHook) != address(0)) { onKeyCancelHook.onKeyCancel(msg.sender, _keyOwner, refund); } } /** * @dev Determines how much of a refund a key owner would receive if they issued * a cancelAndRefund now. * @param _keyOwner The owner of the key check the refund value for. */ function _getCancelAndRefundValue( address _keyOwner ) private view hasValidKey(_keyOwner) returns (uint refund) { Key storage key = keyByOwner[_keyOwner]; // Math: safeSub is not required since `hasValidKey` confirms timeRemaining is positive uint timeRemaining = key.expirationTimestamp - block.timestamp; if(timeRemaining + freeTrialLength >= expirationDuration) { refund = keyPrice; } else { // Math: using safeMul in case keyPrice or timeRemaining is very large refund = keyPrice.mul(timeRemaining) / expirationDuration; } // Apply the penalty if this is not a free trial if(freeTrialLength == 0 || timeRemaining + freeTrialLength < expirationDuration) { uint penalty = keyPrice.mul(refundPenaltyBasisPoints) / BASIS_POINTS_DEN; if (refund > penalty) { // Math: safeSub is not required since the if confirms this won't underflow refund -= penalty; } else { refund = 0; } } } }
Determines how much of a refund a key owner would receive if they issued a cancelAndRefund now. _keyOwner The owner of the key check the refund value for./ Math: safeSub is not required since `hasValidKey` confirms timeRemaining is positive Math: using safeMul in case keyPrice or timeRemaining is very large Math: safeSub is not required since the if confirms this won't underflow
function _getCancelAndRefundValue( address _keyOwner ) private view hasValidKey(_keyOwner) returns (uint refund) { Key storage key = keyByOwner[_keyOwner]; uint timeRemaining = key.expirationTimestamp - block.timestamp; if(timeRemaining + freeTrialLength >= expirationDuration) { refund = keyPrice; refund = keyPrice.mul(timeRemaining) / expirationDuration; } { uint penalty = keyPrice.mul(refundPenaltyBasisPoints) / BASIS_POINTS_DEN; if (refund > penalty) { refund -= penalty; refund = 0; } } }
1,089,925
pragma solidity ^0.7.6; import 'contracts/interfaces/IUniswapV2Router.sol'; import 'contracts/interfaces/IUniswapV2Pair.sol'; import 'contracts/interfaces/IWETH.sol'; contract Portfolio { //info address public owner; string public name; uint public assetIndex; mapping(uint => Asset) public assets; Config config; //states bool configured; bool rulesSet; bool started; bool running; bool rebalancing; //interfaces IUniswapV2Router iUniswapRouter; IWETH iWeth; //asset structure struct Asset { string name; string symbol; address tokenAddress; uint ratio; uint amount; } //configuration structure struct Config { uint slippage; // basis points out of 10,000 uint swapTimeLimit; // time limit until swap expires in seconds address uniswapRouterAddress; address wethAddress; } constructor(address _owner, string memory _name) public { //set main info owner = _owner; name = _name; assetIndex = 0; //set states configured = false; rulesSet = false; started= false; running = false; rebalancing = false; } modifier onlyOwner { require(msg.sender == owner, "Only owner can call this function."); _; } function addAsset(string memory _name, string memory _symbol, address _address, uint _ratio) onlyOwner public { //create Asset Asset memory asset = Asset(_name, _symbol, _address, _ratio, 0); //map asset assets[assetIndex] = asset; assetIndex++; } function changeAssetRatio(uint _assetIndex, uint _assetRatio) onlyOwner public { assets[_assetIndex].ratio = _assetRatio; } function spreadToAssets() internal { //spread contract balance to assets uint totalAmount = address(this).balance; uint currentAmount = totalAmount; //for every asset for (uint i=0; i<assetIndex; i++) { //if current amount is empty if (currentAmount == 0) { break; } //get asset and ratio Asset memory asset = assets[i]; uint assetRatio = asset.ratio; if (assetRatio == 0) { break; } //calculate amountPerAsset uint amountPerAsset = totalAmount * assetRatio / 10000; //if current amount is more than amount to asset if (amountPerAsset <= currentAmount) { //buy asset for amount buyAsset(i, amountPerAsset); //adjust current amount if (amountPerAsset == currentAmount) { currentAmount = 0; } else { currentAmount -= amountPerAsset; } } else { //buy remaining current amount and set to 0 buyAsset(i, currentAmount); currentAmount = 0; } } } function buyAsset(uint currentIndex, uint amountIn) internal { //set asset data Asset memory asset = assets[currentIndex]; address buyingAddress = asset.tokenAddress; address wethAddress = config.wethAddress; require(amountIn <= address(this).balance, "Can't send more than current balance"); if (buyingAddress == wethAddress) { //deposit to Wrapped WETH iWeth.deposit{value: amountIn}(); } else { //get swap config uint slippage = config.slippage; uint swapTimeLimit = config.swapTimeLimit; //set path address[] memory path = new address[](2); path[0] = wethAddress; path[1] = buyingAddress; //get amounts out uint[] memory amountsOut = iUniswapRouter.getAmountsOut(amountIn, path); uint tokenOutput = amountsOut[1]; //calculate slippage uint amountOutMin = tokenOutput * (10000 - slippage) / 10000; //set deadline uint deadline = block.timestamp + swapTimeLimit; //swap Eth for tokens and set return amounts uint[] memory amounts = iUniswapRouter.swapExactETHForTokens{value: amountIn}(amountOutMin, path, address(this), deadline); } //update balance updateAssetBalance(currentIndex); } function updateAssetBalance(uint currentIndex) internal { Asset memory asset = assets[currentIndex]; //set balance uint balance; //set Weth address address wethAddress = config.wethAddress; if (asset.tokenAddress == wethAddress) { //get balance balance = iWeth.balanceOf(address(this)); } else { //create pair instance IUniswapV2Pair pair = IUniswapV2Pair(asset.tokenAddress); //get balance balance = pair.balanceOf(address(this)); } //update balance assets[currentIndex].amount = balance; } function rebalance() onlyOwner public { //set rebalancing true rebalancing = true; //empty assets emptyAssets(); //spread to assets spreadToAssets(); //set rebalancing back to false rebalancing = false; } function emptyAssets() onlyOwner internal { //for every asset for (uint i=0; i<assetIndex; i++) { //get asset and ratio Asset memory asset = assets[i]; //if asset balance not empty if (asset.amount > 0) { //empty asset emptyAsset(i); } } } function emptyAsset(uint currentIndex) internal { //set asset data Asset memory asset = assets[currentIndex]; address sellingAddress = asset.tokenAddress; address wethAddress = config.wethAddress; //get swap config uint slippage = config.slippage; uint swapTimeLimit = config.swapTimeLimit; require(asset.amount > 0, "Asset is already empty"); if (sellingAddress == wethAddress) { //deposit to Wrapped WETH iWeth.withdraw(asset.amount); } else { //set path address[] memory path = new address[](2); path[0] = sellingAddress; path[1] = wethAddress; //get amounts out uint[] memory amountsOut = iUniswapRouter.getAmountsOut(asset.amount, path); uint tokenOutput = amountsOut[1]; //calculate slippage uint amountOutMin = tokenOutput * (10000 - slippage) / 10000; //set deadline uint deadline = block.timestamp + swapTimeLimit; IUniswapV2Pair pair = IUniswapV2Pair(sellingAddress); pair.approve(address(iUniswapRouter), asset.amount); //swap Eth for tokens and set return amounts iUniswapRouter.swapExactTokensForETH(asset.amount, amountOutMin, path, address(this), deadline); } //update asset balance updateAssetBalance(currentIndex); } function configure(uint _slippage, uint _swapTimeLimit, address _uniswapRouterAddress, address _wethAddress) onlyOwner public { config = Config({ slippage: _slippage, swapTimeLimit: _swapTimeLimit, uniswapRouterAddress: _uniswapRouterAddress, wethAddress:_wethAddress }); //set interface instances iUniswapRouter = IUniswapV2Router(config.uniswapRouterAddress); iWeth = IWETH(config.wethAddress); //set configured to true configured = true; } function rename(string memory newName) onlyOwner public { name = newName; } function deposit() public payable { require(configured, "Configure portfolio"); if (!rebalancing) { spreadToAssets(); } } function withdraw(uint amount) onlyOwner public { //set state rebalancing = true; emptyAssets(); //transfer to owner owner.call{value: amount}(""); spreadToAssets(); rebalancing = false; } function withdrawAll() onlyOwner public { //set state rebalancing = true; emptyAssets(); //transfer to owner owner.call{value: address(this).balance}(""); spreadToAssets(); rebalancing = false; } function getAssetIndex() public view returns (uint) { return assetIndex; } function getAssetDetails(uint i) public view returns (string memory, string memory, address, uint, uint) { return (assets[i].name, assets[i].symbol, assets[i].tokenAddress, assets[i].ratio, assets[i].amount); } receive() external payable { deposit(); } }
create Assetmap asset
function addAsset(string memory _name, string memory _symbol, address _address, uint _ratio) onlyOwner public { Asset memory asset = Asset(_name, _symbol, _address, _ratio, 0); assets[assetIndex] = asset; assetIndex++; }
12,552,205
pragma solidity ^0.4.11; contract FundariaToken { string public constant name = "Fundaria Token"; string public constant symbol = "RI"; uint public totalSupply; // how many tokens supplied at the moment uint public supplyLimit; // how many tokens can be supplied uint public course; // course wei for token mapping(address=>uint256) public balanceOf; // owned tokens mapping(address=>mapping(address=>uint256)) public allowance; // allowing third parties to transfer tokens mapping(address=>bool) public allowedAddresses; // allowed addresses to manage some functions address public fundariaPoolAddress; // ether source for Fundaria development address creator; // creator address of this contract event SuppliedTo(address indexed _to, uint _value); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event SupplyLimitChanged(uint newLimit, uint oldLimit); event AllowedAddressAdded(address _address); event CourseChanged(uint newCourse, uint oldCourse); function FundariaToken() { allowedAddresses[msg.sender] = true; // add creator address to allowed addresses creator = msg.sender; } // condition to be creator address to run some functions modifier onlyCreator { if(msg.sender == creator) _; } // condition to be allowed address to run some functions modifier isAllowed { if(allowedAddresses[msg.sender]) _; } // set address for Fundaria source of ether function setFundariaPoolAddress(address _fundariaPoolAddress) onlyCreator { fundariaPoolAddress = _fundariaPoolAddress; } // expand allowed addresses with new one function addAllowedAddress(address _address) onlyCreator { allowedAddresses[_address] = true; AllowedAddressAdded(_address); } // remove allowed address function removeAllowedAddress(address _address) onlyCreator { delete allowedAddresses[_address]; } // increase token balance of some address function supplyTo(address _to, uint _value) isAllowed { totalSupply += _value; balanceOf[_to] += _value; SuppliedTo(_to, _value); } // limit total tokens can be supplied function setSupplyLimit(uint newLimit) isAllowed { SupplyLimitChanged(newLimit, supplyLimit); supplyLimit = newLimit; } // set course function setCourse(uint newCourse) isAllowed { CourseChanged(newCourse, course); course = newCourse; } // token for wei according to course function tokenForWei(uint _wei) constant returns(uint) { return _wei/course; } // wei for token according to course function weiForToken(uint _token) constant returns(uint) { return _token*course; } // transfer tokens to another address (owner) function transfer(address _to, uint256 _value) returns (bool success) { if (_to == 0x0 || balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to]) return false; balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); return true; } // setting of availability of tokens transference for third party function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if(_to == 0x0 || balanceOf[_from] < _value || _value > allowance[_from][msg.sender]) return false; balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } // approving transference of tokens for third party function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // Prevents accidental sending of ether function () { throw; } }
approving transference of tokens for third party
function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
13,128,427
pragma solidity ^0.6.0; /** * 加解密函数 */ library EncryptUtils { /** * 校验签名 * orgContent: 原文 * sign:签名 * targetAdress: 公钥 */ function verificate(string memory orgContent,string memory sign,address targetAdress) public pure returns(bool) { //solidity 有4个取散列的方法:keccak256,sha3,sha256,ripemd160;其中ripemd160返回的是bytes20,不符合要求;sha3的算法与keccak256相同 bytes memory signature = bytes(sign); bytes32 r = bytesToBytes32(slice(signature,0,32)); bytes32 s = bytesToBytes32(slice(signature,32,32)); uint8 v = bytesToUint(slice(signature,64,1)); address addr = ecrecover(sha256(bytes(orgContent)),v,r,s); return addr==targetAdress; } function slice(bytes memory data,uint start,uint len) public pure returns(bytes memory){ bytes memory b=new bytes(len); for(uint i=0;i<len;i++){ b[i]=data[i+start]; } return b; } function bytesToBytes32(bytes memory source) public pure returns(bytes32 result){ assembly{ result :=mload(add(source,32)) } } function bytesToUint(bytes memory b) public pure returns (uint8){ uint8 number = 0; for(uint64 i= 0; i<b.length; i++){ number = uint8(number + uint8(b[i])*(2**(8*(b.length-(i+1))))); } return number; } function uintToBytes(uint x) public pure returns (bytes memory b){ // bytes memory b; // uint index = 0; // while(i>0){ // b[index]=byte(i%256); // index++; // } // return b; // assembly { // b := mload(0x10) // mstore(b, 0x20) // mstore(add(b, 0x20), x) // } b = new bytes(32); assembly { mstore(add(b, 32), x) } // b = new bytes(32); // for (uint i = 0; i < 32; i++) { // b[i] = byte(uint8(x / (2**(8*(31 - i))))); // } } /** * 把16进制字符串解析成bytes数组 */ function parseBytes(string memory s) public pure returns(bytes memory){ bytes memory numEle = bytes("0123456789abcdef"); bytes memory numEleUpper = bytes("0123456789ABCDEF"); bytes memory bys = bytes(s); uint64 from = 0; if(bys[0]==bytes("0")[0] && bys[1]==bytes("x")[0]){ from+=2; } //uint len = bys.length-from; //bytes memory b=new bytes(len/2); uint256 result = 0; for(uint i=bys.length-1;i>=from;i--){ bool hasFound = false; for(uint j=0;j<numEle.length;j++){ if(numEle[j]==bys[i]){ result = result*16+j; hasFound = true; break; } } if(!hasFound){ for(uint j=0;j<numEleUpper.length;j++){ if(numEleUpper[j]==bys[i]){ result = result*16+j; hasFound = true; break; } } } require(hasFound,"Invalid char"); } // if(len%2!=0){ // len++; // } return uintToBytes(result); } }
bytes memory b; uint index = 0; while(i>0){ b[index]=byte(i%256); index++; } return b; assembly { b := mload(0x10) mstore(b, 0x20) mstore(add(b, 0x20), x) } b = new bytes(32); for (uint i = 0; i < 32; i++) { b[i] = byte(uint8(x / (2(8(31 - i))))); }
function uintToBytes(uint x) public pure returns (bytes memory b){ b = new bytes(32); }
7,309,630
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_ECDSAContractAccount } from "../../iOVM/accounts/iOVM_ECDSAContractAccount.sol"; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_ECDSAUtils } from "../../libraries/utils/Lib_ECDSAUtils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; import { Lib_SafeMathWrapper } from "../../libraries/wrappers/Lib_SafeMathWrapper.sol"; /** * @title OVM_ECDSAContractAccount * @dev The ECDSA Contract Account can be used as the implementation for a ProxyEOA deployed by the * ovmCREATEEOA operation. It enables backwards compatibility with Ethereum's Layer 1, by * providing eth_sign and EIP155 formatted transaction encodings. * * Compiler used: solc * Runtime target: OVM */ contract OVM_ECDSAContractAccount is iOVM_ECDSAContractAccount { /************* * Constants * *************/ // TODO: should be the amount sufficient to cover the gas costs of all of the transactions up // to and including the CALL/CREATE which forms the entrypoint of the transaction. uint256 constant EXECUTION_VALIDATION_GAS_OVERHEAD = 25000; address constant ETH_ERC20_ADDRESS = 0x4200000000000000000000000000000000000006; /******************** * Public Functions * ********************/ /** * Executes a signed transaction. * @param _transaction Signed EOA transaction. * @param _signatureType Hashing scheme used for the transaction (e.g., ETH signed message). * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. * @return Whether or not the call returned (rather than reverted). * @return Data returned by the call. */ function execute( bytes memory _transaction, Lib_OVMCodec.EOASignatureType _signatureType, uint8 _v, bytes32 _r, bytes32 _s ) override public returns ( bool, bytes memory ) { bool isEthSign = _signatureType == Lib_OVMCodec.EOASignatureType.ETH_SIGNED_MESSAGE; // Address of this contract within the ovm (ovmADDRESS) should be the same as the // recovered address of the user who signed this message. This is how we manage to shim // account abstraction even though the user isn't a contract. // Need to make sure that the transaction nonce is right and bump it if so. Lib_SafeExecutionManagerWrapper.safeREQUIRE( Lib_ECDSAUtils.recover( _transaction, isEthSign, _v, _r, _s ) == Lib_SafeExecutionManagerWrapper.safeADDRESS(), "Signature provided for EOA transaction execution is invalid." ); Lib_OVMCodec.EIP155Transaction memory decodedTx = Lib_OVMCodec.decodeEIP155Transaction(_transaction, isEthSign); // Need to make sure that the transaction chainId is correct. Lib_SafeExecutionManagerWrapper.safeREQUIRE( decodedTx.chainId == Lib_SafeExecutionManagerWrapper.safeCHAINID(), "Transaction chainId does not match expected OVM chainId." ); // Need to make sure that the transaction nonce is right. Lib_SafeExecutionManagerWrapper.safeREQUIRE( decodedTx.nonce == Lib_SafeExecutionManagerWrapper.safeGETNONCE(), "Transaction nonce does not match the expected nonce." ); // TEMPORARY: Disable gas checks for mainnet. // // Need to make sure that the gas is sufficient to execute the transaction. // Lib_SafeExecutionManagerWrapper.safeREQUIRE( // gasleft() >= Lib_SafeMathWrapper.add(decodedTx.gasLimit, EXECUTION_VALIDATION_GAS_OVERHEAD), // "Gas is not sufficient to execute the transaction." // ); // Transfer fee to relayer. address relayer = Lib_SafeExecutionManagerWrapper.safeCALLER(); uint256 fee = Lib_SafeMathWrapper.mul(decodedTx.gasLimit, decodedTx.gasPrice); (bool success, ) = Lib_SafeExecutionManagerWrapper.safeCALL( gasleft(), ETH_ERC20_ADDRESS, abi.encodeWithSignature("transfer(address,uint256)", relayer, fee) ); Lib_SafeExecutionManagerWrapper.safeREQUIRE( success == true, "Fee was not transferred to relayer." ); // Contract creations are signalled by sending a transaction to the zero address. if (decodedTx.to == address(0)) { (address created, bytes memory revertData) = Lib_SafeExecutionManagerWrapper.safeCREATE( gasleft(), decodedTx.data ); // Return true if the contract creation succeeded, false w/ revertData otherwise. if (created != address(0)) { return (true, abi.encode(created)); } else { return (false, revertData); } } else { // We only want to bump the nonce for `ovmCALL` because `ovmCREATE` automatically bumps // the nonce of the calling account. Normally an EOA would bump the nonce for both // cases, but since this is a contract we'd end up bumping the nonce twice. Lib_SafeExecutionManagerWrapper.safeINCREMENTNONCE(); return Lib_SafeExecutionManagerWrapper.safeCALL( gasleft(), decodedTx.to, decodedTx.data ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_ECDSAUtils } from "../../libraries/utils/Lib_ECDSAUtils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title OVM_ProxyEOA * @dev The Proxy EOA contract uses a delegate call to execute the logic in an implementation contract. * In combination with the logic implemented in the ECDSA Contract Account, this enables a form of upgradable * 'account abstraction' on layer 2. * * Compiler used: solc * Runtime target: OVM */ contract OVM_ProxyEOA { /************* * Constants * *************/ bytes32 constant IMPLEMENTATION_KEY = 0xdeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddead; /*************** * Constructor * ***************/ /** * @param _implementation Address of the initial implementation contract. */ constructor( address _implementation ) { _setImplementation(_implementation); } /********************* * Fallback Function * *********************/ fallback() external { (bool success, bytes memory returndata) = Lib_SafeExecutionManagerWrapper.safeDELEGATECALL( gasleft(), getImplementation(), msg.data ); if (success) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { Lib_SafeExecutionManagerWrapper.safeREVERT( string(returndata) ); } } /******************** * Public Functions * ********************/ /** * Changes the implementation address. * @param _implementation New implementation address. */ function upgrade( address _implementation ) external { Lib_SafeExecutionManagerWrapper.safeREQUIRE( Lib_SafeExecutionManagerWrapper.safeADDRESS() == Lib_SafeExecutionManagerWrapper.safeCALLER(), "EOAs can only upgrade their own EOA implementation" ); _setImplementation(_implementation); } /** * Gets the address of the current implementation. * @return Current implementation address. */ function getImplementation() public returns ( address ) { return Lib_Bytes32Utils.toAddress( Lib_SafeExecutionManagerWrapper.safeSLOAD( IMPLEMENTATION_KEY ) ); } /********************** * Internal Functions * **********************/ function _setImplementation( address _implementation ) internal { Lib_SafeExecutionManagerWrapper.safeSSTORE( IMPLEMENTATION_KEY, Lib_Bytes32Utils.fromAddress(_implementation) ); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_ErrorUtils } from "../../libraries/utils/Lib_ErrorUtils.sol"; /* Interface Imports */ import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol"; /* Contract Imports */ import { OVM_ECDSAContractAccount } from "../accounts/OVM_ECDSAContractAccount.sol"; import { OVM_ProxyEOA } from "../accounts/OVM_ProxyEOA.sol"; import { OVM_DeployerWhitelist } from "../predeploys/OVM_DeployerWhitelist.sol"; /** * @title OVM_ExecutionManager * @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed * environment allowing us to execute OVM transactions deterministically on either Layer 1 or * Layer 2. * The EM's run() function is the first function called during the execution of any * transaction on L2. * For each context-dependent EVM operation the EM has a function which implements a corresponding * OVM operation, which will read state from the State Manager contract. * The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any * context-dependent operations. * * Compiler used: solc * Runtime target: EVM */ contract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver { /******************************** * External Contract References * ********************************/ iOVM_SafetyChecker internal ovmSafetyChecker; iOVM_StateManager internal ovmStateManager; /******************************* * Execution Context Variables * *******************************/ GasMeterConfig internal gasMeterConfig; GlobalContext internal globalContext; TransactionContext internal transactionContext; MessageContext internal messageContext; TransactionRecord internal transactionRecord; MessageRecord internal messageRecord; /************************** * Gas Metering Constants * **************************/ address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5; uint256 constant NUISANCE_GAS_SLOAD = 20000; uint256 constant NUISANCE_GAS_SSTORE = 20000; uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000; uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100; uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000; /************************** * Default Context Values * **************************/ uint256 constant DEFAULT_UINT256 = 0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d; address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, GasMeterConfig memory _gasMeterConfig, GlobalContext memory _globalContext ) Lib_AddressResolver(_libAddressManager) { ovmSafetyChecker = iOVM_SafetyChecker(resolve("OVM_SafetyChecker")); gasMeterConfig = _gasMeterConfig; globalContext = _globalContext; _resetContext(); } /********************** * Function Modifiers * **********************/ /** * Applies dynamically-sized refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of the ovmOPCODE is fixed. * @param _cost Desired gas cost for the function after the refund. */ modifier netGasCost( uint256 _cost ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund everything *except* the specified cost. if (_cost < gasUsed) { transactionRecord.ovmGasRefund += gasUsed - _cost; } } /** * Applies a fixed-size gas refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered. * @param _discount Amount of gas cost to refund for the ovmOPCODE. */ modifier fixedGasDiscount( uint256 _discount ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund the specified _discount, unless this risks underflow. if (_discount < gasUsed) { transactionRecord.ovmGasRefund += _discount; } else { // refund all we can without risking underflow. transactionRecord.ovmGasRefund += gasUsed; } } /** * Makes sure we're not inside a static context. */ modifier notStatic() { if (messageContext.isStatic == true) { _revertWithFlag(RevertFlag.STATIC_VIOLATION); } _; } /************************************ * Transaction Execution Entrypoint * ************************************/ /** * Starts the execution of a transaction via the OVM_ExecutionManager. * @param _transaction Transaction data to be executed. * @param _ovmStateManager iOVM_StateManager implementation providing account state. */ function run( Lib_OVMCodec.Transaction memory _transaction, address _ovmStateManager ) override public { // Make sure that run() is not re-enterable. This condition should awlways be satisfied // Once run has been called once, due to the behvaior of _isValidInput(). if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // Store our OVM_StateManager instance (significantly easier than attempting to pass the // address around in calldata). ovmStateManager = iOVM_StateManager(_ovmStateManager); // Make sure this function can't be called by anyone except the owner of the // OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because // this would make the `run` itself invalid. require( // This method may return false during fraud proofs, but always returns true in L2 nodes' State Manager precompile. ovmStateManager.isAuthenticated(msg.sender), "Only authenticated addresses in ovmStateManager can call this function" ); // Initialize the execution context, must be initialized before we perform any gas metering // or we'll throw a nuisance gas error. _initContext(_transaction); // TEMPORARY: Gas metering is disabled for minnet. // // Check whether we need to start a new epoch, do so if necessary. // _checkNeedsNewEpoch(_transaction.timestamp); // Make sure the transaction's gas limit is valid. We don't revert here because we reserve // reverts for INVALID_STATE_ACCESS. if (_isValidInput(_transaction) == false) { _resetContext(); return; } // TEMPORARY: Gas metering is disabled for minnet. // // Check gas right before the call to get total gas consumed by OVM transaction. // uint256 gasProvided = gasleft(); // Run the transaction, make sure to meter the gas usage. ovmCALL( _transaction.gasLimit - gasMeterConfig.minTransactionGasLimit, _transaction.entrypoint, _transaction.data ); // TEMPORARY: Gas metering is disabled for minnet. // // Update the cumulative gas based on the amount of gas used. // uint256 gasUsed = gasProvided - gasleft(); // _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin); // Wipe the execution context. _resetContext(); } /****************************** * Opcodes: Execution Context * ******************************/ /** * @notice Overrides CALLER. * @return _CALLER Address of the CALLER within the current message context. */ function ovmCALLER() override public view returns ( address _CALLER ) { return messageContext.ovmCALLER; } /** * @notice Overrides ADDRESS. * @return _ADDRESS Active ADDRESS within the current message context. */ function ovmADDRESS() override public view returns ( address _ADDRESS ) { return messageContext.ovmADDRESS; } /** * @notice Overrides TIMESTAMP. * @return _TIMESTAMP Value of the TIMESTAMP within the transaction context. */ function ovmTIMESTAMP() override public view returns ( uint256 _TIMESTAMP ) { return transactionContext.ovmTIMESTAMP; } /** * @notice Overrides NUMBER. * @return _NUMBER Value of the NUMBER within the transaction context. */ function ovmNUMBER() override public view returns ( uint256 _NUMBER ) { return transactionContext.ovmNUMBER; } /** * @notice Overrides GASLIMIT. * @return _GASLIMIT Value of the block's GASLIMIT within the transaction context. */ function ovmGASLIMIT() override public view returns ( uint256 _GASLIMIT ) { return transactionContext.ovmGASLIMIT; } /** * @notice Overrides CHAINID. * @return _CHAINID Value of the chain's CHAINID within the global context. */ function ovmCHAINID() override public view returns ( uint256 _CHAINID ) { return globalContext.ovmCHAINID; } /********************************* * Opcodes: L2 Execution Context * *********************************/ /** * @notice Specifies from which L1 rollup queue this transaction originated from. * @return _queueOrigin Address of the ovmL1QUEUEORIGIN within the current message context. */ function ovmL1QUEUEORIGIN() override public view returns ( Lib_OVMCodec.QueueOrigin _queueOrigin ) { return transactionContext.ovmL1QUEUEORIGIN; } /** * @notice Specifies which L1 account, if any, sent this transaction by calling enqueue(). * @return _l1TxOrigin Address of the account which sent the tx into L2 from L1. */ function ovmL1TXORIGIN() override public view returns ( address _l1TxOrigin ) { return transactionContext.ovmL1TXORIGIN; } /******************** * Opcodes: Halting * ********************/ /** * @notice Overrides REVERT. * @param _data Bytes data to pass along with the REVERT. */ function ovmREVERT( bytes memory _data ) override public { _revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data); } /****************************** * Opcodes: Contract Creation * ******************************/ /** * @notice Overrides CREATE. * @param _bytecode Code to be used to CREATE a new contract. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE( bytes memory _bytecode ) override public notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE address. address contractAddress = Lib_EthUtils.getAddressForCREATE( creator, _getAccountNonce(creator) ); return _createContract( contractAddress, _bytecode ); } /** * @notice Overrides CREATE2. * @param _bytecode Code to be used to CREATE2 a new contract. * @param _salt Value used to determine the contract's address. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE2( bytes memory _bytecode, bytes32 _salt ) override public notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE2 address. address contractAddress = Lib_EthUtils.getAddressForCREATE2( creator, _bytecode, _salt ); return _createContract( contractAddress, _bytecode ); } /******************************* * Account Abstraction Opcodes * ******************************/ /** * Retrieves the nonce of the current ovmADDRESS. * @return _nonce Nonce of the current contract. */ function ovmGETNONCE() override public returns ( uint256 _nonce ) { return _getAccountNonce(ovmADDRESS()); } /** * Bumps the nonce of the current ovmADDRESS by one. */ function ovmINCREMENTNONCE() override public notStatic { address account = ovmADDRESS(); uint256 nonce = _getAccountNonce(account); // Prevent overflow. if (nonce + 1 > nonce) { _setAccountNonce(account, nonce + 1); } } /** * Creates a new EOA contract account, for account abstraction. * @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks * because the contract we're creating is trusted (no need to do safety checking or to * handle unexpected reverts). Doesn't need to return an address because the address is * assumed to be the user's actual address. * @param _messageHash Hash of a message signed by some user, for verification. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) override public notStatic { // Recover the EOA address from the message hash and signature parameters. Since we do the // hashing in advance, we don't have handle different message hashing schemes. Even if this // function were to return the wrong address (rather than explicitly returning the zero // address), the rest of the transaction would simply fail (since there's no EOA account to // actually execute the transaction). address eoa = ecrecover( _messageHash, _v + 27, _r, _s ); // Invalid signature is a case we proactively handle with a revert. We could alternatively // have this function return a `success` boolean, but this is just easier. if (eoa == address(0)) { ovmREVERT(bytes("Signature provided for EOA contract creation is invalid.")); } // If the user already has an EOA account, then there's no need to perform this operation. if (_hasEmptyAccount(eoa) == false) { return; } // We always need to initialize the contract with the default account values. _initPendingAccount(eoa); // Temporarily set the current address so it's easier to access on L2. address prevADDRESS = messageContext.ovmADDRESS; messageContext.ovmADDRESS = eoa; // Now actually create the account and get its bytecode. We're not worried about reverts // (other than out of gas, which we can't capture anyway) because this contract is trusted. OVM_ProxyEOA proxyEOA = new OVM_ProxyEOA(0x4200000000000000000000000000000000000003); // Reset the address now that we're done deploying. messageContext.ovmADDRESS = prevADDRESS; // Commit the account with its final values. _commitPendingAccount( eoa, address(proxyEOA), keccak256(Lib_EthUtils.getCode(address(proxyEOA))) ); _setAccountNonce(eoa, 0); } /********************************* * Opcodes: Contract Interaction * *********************************/ /** * @notice Overrides CALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(100000) returns ( bool _success, bytes memory _returndata ) { // CALL updates the CALLER and ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; return _callContract( nextMessageContext, _gasLimit, _address, _calldata ); } /** * @notice Overrides STATICCALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmSTATICCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(80000) returns ( bool _success, bytes memory _returndata ) { // STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static context. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.isStatic = true; return _callContract( nextMessageContext, _gasLimit, _address, _calldata ); } /** * @notice Overrides DELEGATECALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmDELEGATECALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(40000) returns ( bool _success, bytes memory _returndata ) { // DELEGATECALL does not change anything about the message context. MessageContext memory nextMessageContext = messageContext; return _callContract( nextMessageContext, _gasLimit, _address, _calldata ); } /************************************ * Opcodes: Contract Storage Access * ************************************/ /** * @notice Overrides SLOAD. * @param _key 32 byte key of the storage slot to load. * @return _value 32 byte value of the requested storage slot. */ function ovmSLOAD( bytes32 _key ) override public netGasCost(40000) returns ( bytes32 _value ) { // We always SLOAD from the storage of ADDRESS. address contractAddress = ovmADDRESS(); return _getContractStorage( contractAddress, _key ); } /** * @notice Overrides SSTORE. * @param _key 32 byte key of the storage slot to set. * @param _value 32 byte value for the storage slot. */ function ovmSSTORE( bytes32 _key, bytes32 _value ) override public notStatic netGasCost(60000) { // We always SSTORE to the storage of ADDRESS. address contractAddress = ovmADDRESS(); _putContractStorage( contractAddress, _key, _value ); } /********************************* * Opcodes: Contract Code Access * *********************************/ /** * @notice Overrides EXTCODECOPY. * @param _contract Address of the contract to copy code from. * @param _offset Offset in bytes from the start of contract code to copy beyond. * @param _length Total number of bytes to copy from the contract's code. * @return _code Bytes of code copied from the requested contract. */ function ovmEXTCODECOPY( address _contract, uint256 _offset, uint256 _length ) override public returns ( bytes memory _code ) { // `ovmEXTCODECOPY` is the only overridden opcode capable of producing exactly one byte of // return data. By blocking reads of one byte, we're able to use the condition that an // OVM_ExecutionManager function return value having a length of exactly one byte indicates // an error without an explicit revert. If users were able to read a single byte, they // could forcibly trigger behavior that should only be available to this contract. uint256 length = _length == 1 ? 2 : _length; return Lib_EthUtils.getCode( _getAccountEthAddress(_contract), _offset, length ); } /** * @notice Overrides EXTCODESIZE. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function ovmEXTCODESIZE( address _contract ) override public returns ( uint256 _EXTCODESIZE ) { return Lib_EthUtils.getCodeSize( _getAccountEthAddress(_contract) ); } /** * @notice Overrides EXTCODEHASH. * @param _contract Address of the contract to query the hash of. * @return _EXTCODEHASH Hash of the requested contract. */ function ovmEXTCODEHASH( address _contract ) override public returns ( bytes32 _EXTCODEHASH ) { return Lib_EthUtils.getCodeHash( _getAccountEthAddress(_contract) ); } /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view override returns ( uint256 _maxTransactionGasLimit ) { return gasMeterConfig.maxTransactionGasLimit; } /******************************************** * Public Functions: Deployment Whitelisting * ********************************************/ /** * Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2, and reverts if not. * @param _deployerAddress Address attempting to deploy a contract. */ function _checkDeployerAllowed( address _deployerAddress ) internal { // From an OVM semantics perspective, this will appear identical to // the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to. (bool success, bytes memory data) = ovmCALL( gasleft(), 0x4200000000000000000000000000000000000002, abi.encodeWithSignature("isDeployerAllowed(address)", _deployerAddress) ); bool isAllowed = abi.decode(data, (bool)); if (!isAllowed || !success) { _revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED); } } /******************************************** * Internal Functions: Contract Interaction * ********************************************/ /** * Creates a new contract and associates it with some contract address. * @param _contractAddress Address to associate the created contract with. * @param _bytecode Bytecode to be used to create the contract. * @return Final OVM contract address. * @return Revertdata, if and only if the creation threw an exception. */ function _createContract( address _contractAddress, bytes memory _bytecode ) internal returns ( address, bytes memory ) { // We always update the nonce of the creating account, even if the creation fails. _setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1); // We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point // to the contract's associated address and CALLER to point to the previous ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = messageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _contractAddress; // Run the common logic which occurs between call-type and create-type messages, // passing in the creation bytecode and `true` to trigger create-specific logic. (bool success, bytes memory data) = _handleExternalMessage( nextMessageContext, gasleft(), _contractAddress, _bytecode, true ); // Yellow paper requires that address returned is zero if the contract deployment fails. return ( success ? _contractAddress : address(0), data ); } /** * Calls the deployed contract associated with a given address. * @param _nextMessageContext Message context to be used for the call. * @param _gasLimit Amount of gas to be passed into this call. * @param _contract OVM address to be called. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function _callContract( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { // We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2 geth. // So, we block calls to these addresses since they are not safe to run as an OVM contract itself. if ( (uint256(_contract) & uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000)) == uint256(0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000) ) { // EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604 return (true, hex''); } // Both 0x0000... and the EVM precompiles have the same address on L1 and L2 --> no trie lookup needed. address codeContractAddress = uint(_contract) < 100 ? _contract : _getAccountEthAddress(_contract); return _handleExternalMessage( _nextMessageContext, _gasLimit, codeContractAddress, _calldata, false ); } /** * Handles all interactions which involve the execution manager calling out to untrusted code (both calls and creates). * Ensures that OVM-related measures are enforced, including L2 gas refunds, nuisance gas, and flagged reversions. * * @param _nextMessageContext Message context to be used for the external message. * @param _gasLimit Amount of gas to be passed into this message. * @param _contract OVM address being called or deployed to * @param _data Data for the message (either calldata or creation code) * @param _isCreate Whether this is a create-type message. * @return Whether or not the message (either a call or deployment) succeeded. * @return Data returned by the message. */ function _handleExternalMessage( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _data, bool _isCreate ) internal returns ( bool, bytes memory ) { // We need to switch over to our next message context for the duration of this call. MessageContext memory prevMessageContext = messageContext; _switchMessageContext(prevMessageContext, _nextMessageContext); // Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs // expensive by touching a lot of different accounts or storage slots. Since most contracts // only use a few storage slots during any given transaction, this shouldn't be a limiting // factor. uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft; uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit); messageRecord.nuisanceGasLeft = nuisanceGasLimit; // Make the call and make sure to pass in the gas limit. Another instance of hidden // complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert // behavior can be controlled. In particular, we enforce that flags are passed through // revert data as to retrieve execution metadata that would normally be reverted out of // existence. bool success; bytes memory returndata; if (_isCreate) { // safeCREATE() is a function which replicates a CREATE message, but uses return values // Which match that of CALL (i.e. bool, bytes). This allows many security checks to be // to be shared between untrusted call and create call frames. (success, returndata) = address(this).call( abi.encodeWithSelector( this.safeCREATE.selector, _gasLimit, _data, _contract ) ); } else { (success, returndata) = _contract.call{gas: _gasLimit}(_data); } // Switch back to the original message context now that we're out of the call. _switchMessageContext(_nextMessageContext, prevMessageContext); // Assuming there were no reverts, the message record should be accurate here. We'll update // this value in the case of a revert. uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft; // Reverts at this point are completely OK, but we need to make a few updates based on the // information passed through the revert. if (success == false) { ( RevertFlag flag, uint256 nuisanceGasLeftPostRevert, uint256 ovmGasRefund, bytes memory returndataFromFlag ) = _decodeRevertData(returndata); // INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the // parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must // halt any further transaction execution that could impact the execution result. if (flag == RevertFlag.INVALID_STATE_ACCESS) { _revertWithFlag(flag); } // INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't // dependent on the input state, so we can just handle them like standard reverts. Our only change here // is to record the gas refund reported by the call (enforced by safety checking). if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE || flag == RevertFlag.STATIC_VIOLATION || flag == RevertFlag.CREATOR_NOT_ALLOWED ) { transactionRecord.ovmGasRefund = ovmGasRefund; } // INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the // flag, *not* the full encoded flag. All other revert types return no data. if ( flag == RevertFlag.INTENTIONAL_REVERT || _isCreate ) { returndata = returndataFromFlag; } else { returndata = hex''; } // Reverts mean we need to use up whatever "nuisance gas" was used by the call. // EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message // to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they // run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags // will simply pass up the remaining nuisance gas. nuisanceGasLeft = nuisanceGasLeftPostRevert; } // We need to reset the nuisance gas back to its original value minus the amount used here. messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft); return ( success, returndata ); } /** * Handles the creation-specific safety measures required for OVM contract deployment. * This function sanitizes the return types for creation messages to match calls (bool, bytes), * by being an external function which the EM can call, that mimics the success/fail case of the CREATE. * This allows for consistent handling of both types of messages in _handleExternalMessage(). * Having this step occur as a separate call frame also allows us to easily revert the * contract deployment in the event that the code is unsafe. * * @param _gasLimit Amount of gas to be passed into this creation. * @param _creationCode Code to pass into CREATE for deployment. * @param _address OVM address being deployed to. */ function safeCREATE( uint _gasLimit, bytes memory _creationCode, address _address ) external { // The only way this should callable is from within _createContract(), // and it should DEFINITELY not be callable by a non-EM code contract. if (msg.sender != address(this)) { return; } // Check that there is not already code at this address. if (_hasEmptyAccount(_address) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.CREATE_COLLISION, Lib_ErrorUtils.encodeRevertString("A contract has already been deployed to this address") ); } // Check the creation bytecode against the OVM_SafetyChecker. if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, Lib_ErrorUtils.encodeRevertString("Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?") ); } // We always need to initialize the contract with the default account values. _initPendingAccount(_address); // Actually execute the EVM create message. // NOTE: The inline assembly below means we can NOT make any evm calls between here and then. address ethAddress = Lib_EthUtils.createContract(_creationCode); if (ethAddress == address(0)) { // If the creation fails, the EVM lets us grab its revert data. This may contain a revert flag // to be used above in _handleExternalMessage, so we pass the revert data back up unmodified. assembly { returndatacopy(0,0,returndatasize()) revert(0, returndatasize()) } } // Again simply checking that the deployed code is safe too. Contracts can generate // arbitrary deployment code, so there's no easy way to analyze this beforehand. bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress); if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, Lib_ErrorUtils.encodeRevertString("Constructor attempted to deploy unsafe bytecode.") ); } // Contract creation didn't need to be reverted and the bytecode is safe. We finish up by // associating the desired address with the newly created contract's code hash and address. _commitPendingAccount( _address, ethAddress, Lib_EthUtils.getCodeHash(ethAddress) ); } /****************************************** * Internal Functions: State Manipulation * ******************************************/ /** * Checks whether an account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account exists. */ function _hasAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasAccount(_address); } /** * Checks whether a known empty account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account empty exists. */ function _hasEmptyAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasEmptyAccount(_address); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function _setAccountNonce( address _address, uint256 _nonce ) internal { _checkAccountChange(_address); ovmStateManager.setAccountNonce(_address, _nonce); } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return _nonce Nonce of the account. */ function _getAccountNonce( address _address ) internal returns ( uint256 _nonce ) { _checkAccountLoad(_address); return ovmStateManager.getAccountNonce(_address); } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return _ethAddress Corresponding Ethereum address. */ function _getAccountEthAddress( address _address ) internal returns ( address _ethAddress ) { _checkAccountLoad(_address); return ovmStateManager.getAccountEthAddress(_address); } /** * Creates the default account object for the given address. * @param _address Address of the account create. */ function _initPendingAccount( address _address ) internal { // Although it seems like `_checkAccountChange` would be more appropriate here, we don't // actually consider an account "changed" until it's inserted into the state (in this case // by `_commitPendingAccount`). _checkAccountLoad(_address); ovmStateManager.initPendingAccount(_address); } /** * Stores additional relevant data for a new account, thereby "committing" it to the state. * This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract * creation. * @param _address Address of the account to commit. * @param _ethAddress Address of the associated deployed contract. * @param _codeHash Hash of the code stored at the address. */ function _commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) internal { _checkAccountChange(_address); ovmStateManager.commitPendingAccount( _address, _ethAddress, _codeHash ); } /** * Retrieves the value of a storage slot. * @param _contract Address of the contract to query. * @param _key 32 byte key of the storage slot. * @return _value 32 byte storage slot value. */ function _getContractStorage( address _contract, bytes32 _key ) internal returns ( bytes32 _value ) { _checkContractStorageLoad(_contract, _key); return ovmStateManager.getContractStorage(_contract, _key); } /** * Sets the value of a storage slot. * @param _contract Address of the contract to modify. * @param _key 32 byte key of the storage slot. * @param _value 32 byte storage slot value. */ function _putContractStorage( address _contract, bytes32 _key, bytes32 _value ) internal { // We don't set storage if the value didn't change. Although this acts as a convenient // optimization, it's also necessary to avoid the case in which a contract with no storage // attempts to store the value "0" at any key. Putting this value (and therefore requiring // that the value be committed into the storage trie after execution) would incorrectly // modify the storage root. if (_getContractStorage(_contract, _key) == _value) { return; } _checkContractStorageChange(_contract, _key); ovmStateManager.putContractStorage(_contract, _key, _value); } /** * Validation whenever a contract needs to be loaded. Checks that the account exists, charges * nuisance gas if the account hasn't been loaded before. * @param _address Address of the account to load. */ function _checkAccountLoad( address _address ) internal { // See `_checkContractStorageLoad` for more information. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // See `_checkContractStorageLoad` for more information. if (ovmStateManager.hasAccount(_address) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the account has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that an account is loaded. ( bool _wasAccountAlreadyLoaded ) = ovmStateManager.testAndSetAccountLoaded(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyLoaded == false) { _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a contract needs to be changed. Checks that the account exists, charges * nuisance gas if the account hasn't been changed before. * @param _address Address of the account to change. */ function _checkAccountChange( address _address ) internal { // Start by checking for a load as we only want to charge nuisance gas proportional to // contract size once. _checkAccountLoad(_address); // Check whether the account has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that an account is changed. ( bool _wasAccountAlreadyChanged ) = ovmStateManager.testAndSetAccountChanged(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyChanged == false) { ovmStateManager.incrementTotalUncommittedAccounts(); _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a slot needs to be loaded. Checks that the account exists, charges * nuisance gas if the slot hasn't been loaded before. * @param _contract Address of the account to load from. * @param _key 32 byte key to load. */ function _checkContractStorageLoad( address _contract, bytes32 _key ) internal { // Another case of hidden complexity. If we didn't enforce this requirement, then a // contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail // on L1 but not on L2. A contract could use this behavior to prevent the // OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS // allows us to also charge for the full message nuisance gas, because you deserve that for // trying to break the contract in this way. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // We need to make sure that the transaction isn't trying to access storage that hasn't // been provided to the OVM_StateManager. We'll immediately abort if this is the case. // We know that we have enough gas to do this check because of the above test. if (ovmStateManager.hasContractStorage(_contract, _key) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the slot has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that a slot is loaded. ( bool _wasContractStorageAlreadyLoaded ) = ovmStateManager.testAndSetContractStorageLoaded(_contract, _key); // If we hadn't already loaded the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyLoaded == false) { _useNuisanceGas(NUISANCE_GAS_SLOAD); } } /** * Validation whenever a slot needs to be changed. Checks that the account exists, charges * nuisance gas if the slot hasn't been changed before. * @param _contract Address of the account to change. * @param _key 32 byte key to change. */ function _checkContractStorageChange( address _contract, bytes32 _key ) internal { // Start by checking for load to make sure we have the storage slot and that we charge the // "nuisance gas" necessary to prove the storage slot state. _checkContractStorageLoad(_contract, _key); // Check whether the slot has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that a slot is changed. ( bool _wasContractStorageAlreadyChanged ) = ovmStateManager.testAndSetContractStorageChanged(_contract, _key); // If we hadn't already changed the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyChanged == false) { // Changing a storage slot means that we're also going to have to change the // corresponding account, so do an account change check. _checkAccountChange(_contract); ovmStateManager.incrementTotalUncommittedContractStorage(); _useNuisanceGas(NUISANCE_GAS_SSTORE); } } /************************************ * Internal Functions: Revert Logic * ************************************/ /** * Simple encoding for revert data. * @param _flag Flag to revert with. * @param _data Additional user-provided revert data. * @return _revertdata Encoded revert data. */ function _encodeRevertData( RevertFlag _flag, bytes memory _data ) internal view returns ( bytes memory _revertdata ) { // Out of gas and create exceptions will fundamentally return no data, so simulating it shouldn't either. if ( _flag == RevertFlag.OUT_OF_GAS ) { return bytes(''); } // INVALID_STATE_ACCESS doesn't need to return any data other than the flag. if (_flag == RevertFlag.INVALID_STATE_ACCESS) { return abi.encode( _flag, 0, 0, bytes('') ); } // Just ABI encode the rest of the parameters. return abi.encode( _flag, messageRecord.nuisanceGasLeft, transactionRecord.ovmGasRefund, _data ); } /** * Simple decoding for revert data. * @param _revertdata Revert data to decode. * @return _flag Flag used to revert. * @return _nuisanceGasLeft Amount of nuisance gas unused by the message. * @return _ovmGasRefund Amount of gas refunded during the message. * @return _data Additional user-provided revert data. */ function _decodeRevertData( bytes memory _revertdata ) internal pure returns ( RevertFlag _flag, uint256 _nuisanceGasLeft, uint256 _ovmGasRefund, bytes memory _data ) { // A length of zero means the call ran out of gas, just return empty data. if (_revertdata.length == 0) { return ( RevertFlag.OUT_OF_GAS, 0, 0, bytes('') ); } // ABI decode the incoming data. return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes)); } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. * @param _data Additional user-provided data. */ function _revertWithFlag( RevertFlag _flag, bytes memory _data ) internal view { bytes memory revertdata = _encodeRevertData( _flag, _data ); assembly { revert(add(revertdata, 0x20), mload(revertdata)) } } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. */ function _revertWithFlag( RevertFlag _flag ) internal { _revertWithFlag(_flag, bytes('')); } /****************************************** * Internal Functions: Nuisance Gas Logic * ******************************************/ /** * Computes the nuisance gas limit from the gas limit. * @dev This function is currently using a naive implementation whereby the nuisance gas limit * is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that * this implementation is perfectly fine, but we may change this formula later. * @param _gasLimit Gas limit to compute from. * @return _nuisanceGasLimit Computed nuisance gas limit. */ function _getNuisanceGasLimit( uint256 _gasLimit ) internal view returns ( uint256 _nuisanceGasLimit ) { return _gasLimit < gasleft() ? _gasLimit : gasleft(); } /** * Uses a certain amount of nuisance gas. * @param _amount Amount of nuisance gas to use. */ function _useNuisanceGas( uint256 _amount ) internal { // Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas // refund to be given at the end of the transaction. if (messageRecord.nuisanceGasLeft < _amount) { _revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS); } messageRecord.nuisanceGasLeft -= _amount; } /************************************ * Internal Functions: Gas Metering * ************************************/ /** * Checks whether a transaction needs to start a new epoch and does so if necessary. * @param _timestamp Transaction timestamp. */ function _checkNeedsNewEpoch( uint256 _timestamp ) internal { if ( _timestamp >= ( _getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP) + gasMeterConfig.secondsPerEpoch ) ) { _putGasMetadata( GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP, _timestamp ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS ) ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS ) ); } } /** * Validates the input values of a transaction. * @return _valid Whether or not the transaction data is valid. */ function _isValidInput( Lib_OVMCodec.Transaction memory _transaction ) view internal returns ( bool ) { // Prevent reentrancy to run(): // This check prevents calling run with the default ovmNumber. // Combined with the first check in run(): // if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // It should be impossible to re-enter since run() returns before any other call frames are created. // Since this value is already being written to storage, we save much gas compared to // using the standard nonReentrant pattern. if (_transaction.blockNumber == DEFAULT_UINT256) { return false; } if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) { return false; } return true; } /** * Validates the gas limit for a given transaction. * @param _gasLimit Gas limit provided by the transaction. * param _queueOrigin Queue from which the transaction originated. * @return _valid Whether or not the gas limit is valid. */ function _isValidGasLimit( uint256 _gasLimit, Lib_OVMCodec.QueueOrigin // _queueOrigin ) view internal returns ( bool _valid ) { // Always have to be below the maximum gas limit. if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) { return false; } // Always have to be above the minimum gas limit. if (_gasLimit < gasMeterConfig.minTransactionGasLimit) { return false; } // TEMPORARY: Gas metering is disabled for minnet. return true; // GasMetadataKey cumulativeGasKey; // GasMetadataKey prevEpochGasKey; // if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS; // } else { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS; // } // return ( // ( // _getGasMetadata(cumulativeGasKey) // - _getGasMetadata(prevEpochGasKey) // + _gasLimit // ) < gasMeterConfig.maxGasPerQueuePerEpoch // ); } /** * Updates the cumulative gas after a transaction. * @param _gasUsed Gas used by the transaction. * @param _queueOrigin Queue from which the transaction originated. */ function _updateCumulativeGas( uint256 _gasUsed, Lib_OVMCodec.QueueOrigin _queueOrigin ) internal { GasMetadataKey cumulativeGasKey; if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; } else { cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; } _putGasMetadata( cumulativeGasKey, ( _getGasMetadata(cumulativeGasKey) + gasMeterConfig.minTransactionGasLimit + _gasUsed - transactionRecord.ovmGasRefund ) ); } /** * Retrieves the value of a gas metadata key. * @param _key Gas metadata key to retrieve. * @return _value Value stored at the given key. */ function _getGasMetadata( GasMetadataKey _key ) internal returns ( uint256 _value ) { return uint256(_getContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)) )); } /** * Sets the value of a gas metadata key. * @param _key Gas metadata key to set. * @param _value Value to store at the given key. */ function _putGasMetadata( GasMetadataKey _key, uint256 _value ) internal { _putContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)), bytes32(uint256(_value)) ); } /***************************************** * Internal Functions: Execution Context * *****************************************/ /** * Swaps over to a new message context. * @param _prevMessageContext Context we're switching from. * @param _nextMessageContext Context we're switching to. */ function _switchMessageContext( MessageContext memory _prevMessageContext, MessageContext memory _nextMessageContext ) internal { // Avoid unnecessary the SSTORE. if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) { messageContext.ovmCALLER = _nextMessageContext.ovmCALLER; } // Avoid unnecessary the SSTORE. if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) { messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS; } // Avoid unnecessary the SSTORE. if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) { messageContext.isStatic = _nextMessageContext.isStatic; } } /** * Initializes the execution context. * @param _transaction OVM transaction being executed. */ function _initContext( Lib_OVMCodec.Transaction memory _transaction ) internal { transactionContext.ovmTIMESTAMP = _transaction.timestamp; transactionContext.ovmNUMBER = _transaction.blockNumber; transactionContext.ovmTXGASLIMIT = _transaction.gasLimit; transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin; transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin; transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch; messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit); } /** * Resets the transaction and message context. */ function _resetContext() internal { transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS; transactionContext.ovmTIMESTAMP = DEFAULT_UINT256; transactionContext.ovmNUMBER = DEFAULT_UINT256; transactionContext.ovmGASLIMIT = DEFAULT_UINT256; transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256; transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE; transactionRecord.ovmGasRefund = DEFAULT_UINT256; messageContext.ovmCALLER = DEFAULT_ADDRESS; messageContext.ovmADDRESS = DEFAULT_ADDRESS; messageContext.isStatic = false; messageRecord.nuisanceGasLeft = DEFAULT_UINT256; // Reset the ovmStateManager. ovmStateManager = iOVM_StateManager(address(0)); } /***************************** * L2-only Helper Functions * *****************************/ /** * Unreachable helper function for simulating eth_calls with an OVM message context. * This function will throw an exception in all cases other than when used as a custom entrypoint in L2 Geth to simulate eth_call. * @param _transaction the message transaction to simulate. * @param _from the OVM account the simulated call should be from. */ function simulateMessage( Lib_OVMCodec.Transaction memory _transaction, address _from, iOVM_StateManager _ovmStateManager ) external returns ( bool, bytes memory ) { // Prevent this call from having any effect unless in a custom-set VM frame require(msg.sender == address(0)); ovmStateManager = _ovmStateManager; _initContext(_transaction); messageRecord.nuisanceGasLeft = uint(-1); messageContext.ovmADDRESS = _from; bool isCreate = _transaction.entrypoint == address(0); if (isCreate) { (address created, bytes memory revertData) = ovmCREATE(_transaction.data); if (created == address(0)) { return (false, revertData); } else { // The eth_call RPC endpoint for to = undefined will return the deployed bytecode // in the success case, differing from standard create messages. return (true, Lib_EthUtils.getCode(created)); } } else { return ovmCALL( _transaction.gasLimit, _transaction.entrypoint, _transaction.data ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; /* Interface Imports */ import { iOVM_DeployerWhitelist } from "../../iOVM/predeploys/iOVM_DeployerWhitelist.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title OVM_DeployerWhitelist * @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the * initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts * which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an * ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted. * * Compiler used: solc * Runtime target: OVM */ contract OVM_DeployerWhitelist is iOVM_DeployerWhitelist { /********************** * Contract Constants * **********************/ bytes32 internal constant KEY_INITIALIZED = 0x0000000000000000000000000000000000000000000000000000000000000010; bytes32 internal constant KEY_OWNER = 0x0000000000000000000000000000000000000000000000000000000000000011; bytes32 internal constant KEY_ALLOW_ARBITRARY_DEPLOYMENT = 0x0000000000000000000000000000000000000000000000000000000000000012; /********************** * Function Modifiers * **********************/ /** * Blocks functions to anyone except the contract owner. */ modifier onlyOwner() { address owner = Lib_Bytes32Utils.toAddress( Lib_SafeExecutionManagerWrapper.safeSLOAD( KEY_OWNER ) ); Lib_SafeExecutionManagerWrapper.safeREQUIRE( Lib_SafeExecutionManagerWrapper.safeCALLER() == owner, "Function can only be called by the owner of this contract." ); _; } /******************** * Public Functions * ********************/ /** * Initializes the whitelist. * @param _owner Address of the owner for this contract. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function initialize( address _owner, bool _allowArbitraryDeployment ) override public { bool initialized = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED) ); if (initialized == true) { return; } Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_INITIALIZED, Lib_Bytes32Utils.fromBool(true) ); Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_OWNER, Lib_Bytes32Utils.fromAddress(_owner) ); Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_ALLOW_ARBITRARY_DEPLOYMENT, Lib_Bytes32Utils.fromBool(_allowArbitraryDeployment) ); } /** * Gets the owner of the whitelist. */ function getOwner() override public returns( address ) { return Lib_Bytes32Utils.toAddress( Lib_SafeExecutionManagerWrapper.safeSLOAD( KEY_OWNER ) ); } /** * Adds or removes an address from the deployment whitelist. * @param _deployer Address to update permissions for. * @param _isWhitelisted Whether or not the address is whitelisted. */ function setWhitelistedDeployer( address _deployer, bool _isWhitelisted ) override public onlyOwner { Lib_SafeExecutionManagerWrapper.safeSSTORE( Lib_Bytes32Utils.fromAddress(_deployer), Lib_Bytes32Utils.fromBool(_isWhitelisted) ); } /** * Updates the owner of this contract. * @param _owner Address of the new owner. */ function setOwner( address _owner ) override public onlyOwner { Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_OWNER, Lib_Bytes32Utils.fromAddress(_owner) ); } /** * Updates the arbitrary deployment flag. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function setAllowArbitraryDeployment( bool _allowArbitraryDeployment ) override public onlyOwner { Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_ALLOW_ARBITRARY_DEPLOYMENT, Lib_Bytes32Utils.fromBool(_allowArbitraryDeployment) ); } /** * Permanently enables arbitrary contract deployment and deletes the owner. */ function enableArbitraryContractDeployment() override public onlyOwner { setAllowArbitraryDeployment(true); setOwner(address(0)); } /** * Checks whether an address is allowed to deploy contracts. * @param _deployer Address to check. * @return _allowed Whether or not the address can deploy contracts. */ function isDeployerAllowed( address _deployer ) override public returns ( bool _allowed ) { bool initialized = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED) ); if (initialized == false) { return true; } bool allowArbitraryDeployment = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_ALLOW_ARBITRARY_DEPLOYMENT) ); if (allowArbitraryDeployment == true) { return true; } bool isWhitelisted = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD( Lib_Bytes32Utils.fromAddress(_deployer) ) ); return isWhitelisted; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_ECDSAContractAccount */ interface iOVM_ECDSAContractAccount { /******************** * Public Functions * ********************/ function execute( bytes memory _transaction, Lib_OVMCodec.EOASignatureType _signatureType, uint8 _v, bytes32 _r, bytes32 _s ) external returns (bool _success, bytes memory _returndata); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; interface iOVM_ExecutionManager { /********** * Enums * *********/ enum RevertFlag { OUT_OF_GAS, INTENTIONAL_REVERT, EXCEEDS_NUISANCE_GAS, INVALID_STATE_ACCESS, UNSAFE_BYTECODE, CREATE_COLLISION, STATIC_VIOLATION, CREATOR_NOT_ALLOWED } enum GasMetadataKey { CURRENT_EPOCH_START_TIMESTAMP, CUMULATIVE_SEQUENCER_QUEUE_GAS, CUMULATIVE_L1TOL2_QUEUE_GAS, PREV_EPOCH_SEQUENCER_QUEUE_GAS, PREV_EPOCH_L1TOL2_QUEUE_GAS } /*********** * Structs * ***********/ struct GasMeterConfig { uint256 minTransactionGasLimit; uint256 maxTransactionGasLimit; uint256 maxGasPerQueuePerEpoch; uint256 secondsPerEpoch; } struct GlobalContext { uint256 ovmCHAINID; } struct TransactionContext { Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN; uint256 ovmTIMESTAMP; uint256 ovmNUMBER; uint256 ovmGASLIMIT; uint256 ovmTXGASLIMIT; address ovmL1TXORIGIN; } struct TransactionRecord { uint256 ovmGasRefund; } struct MessageContext { address ovmCALLER; address ovmADDRESS; bool isStatic; } struct MessageRecord { uint256 nuisanceGasLeft; } /************************************ * Transaction Execution Entrypoint * ************************************/ function run( Lib_OVMCodec.Transaction calldata _transaction, address _txStateManager ) external; /******************* * Context Opcodes * *******************/ function ovmCALLER() external view returns (address _caller); function ovmADDRESS() external view returns (address _address); function ovmTIMESTAMP() external view returns (uint256 _timestamp); function ovmNUMBER() external view returns (uint256 _number); function ovmGASLIMIT() external view returns (uint256 _gasLimit); function ovmCHAINID() external view returns (uint256 _chainId); /********************** * L2 Context Opcodes * **********************/ function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin); function ovmL1TXORIGIN() external view returns (address _l1TxOrigin); /******************* * Halting Opcodes * *******************/ function ovmREVERT(bytes memory _data) external; /***************************** * Contract Creation Opcodes * *****************************/ function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata); function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata); /******************************* * Account Abstraction Opcodes * ******************************/ function ovmGETNONCE() external returns (uint256 _nonce); function ovmINCREMENTNONCE() external; function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external; /**************************** * Contract Calling Opcodes * ****************************/ function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); /**************************** * Contract Storage Opcodes * ****************************/ function ovmSLOAD(bytes32 _key) external returns (bytes32 _value); function ovmSSTORE(bytes32 _key, bytes32 _value) external; /************************* * Contract Code Opcodes * *************************/ function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code); function ovmEXTCODESIZE(address _contract) external returns (uint256 _size); function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash); /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_SafetyChecker */ interface iOVM_SafetyChecker { /******************** * Public Functions * ********************/ function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateManager */ interface iOVM_StateManager { /******************* * Data Structures * *******************/ enum ItemState { ITEM_UNTOUCHED, ITEM_LOADED, ITEM_CHANGED, ITEM_COMMITTED } /*************************** * Public Functions: Misc * ***************************/ function isAuthenticated(address _address) external view returns (bool); /*************************** * Public Functions: Setup * ***************************/ function owner() external view returns (address _owner); function ovmExecutionManager() external view returns (address _ovmExecutionManager); function setExecutionManager(address _ovmExecutionManager) external; /************************************ * Public Functions: Account Access * ************************************/ function putAccount(address _address, Lib_OVMCodec.Account memory _account) external; function putEmptyAccount(address _address) external; function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account); function hasAccount(address _address) external view returns (bool _exists); function hasEmptyAccount(address _address) external view returns (bool _exists); function setAccountNonce(address _address, uint256 _nonce) external; function getAccountNonce(address _address) external view returns (uint256 _nonce); function getAccountEthAddress(address _address) external view returns (address _ethAddress); function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot); function initPendingAccount(address _address) external; function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external; function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded); function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged); function commitAccount(address _address) external returns (bool _wasAccountCommitted); function incrementTotalUncommittedAccounts() external; function getTotalUncommittedAccounts() external view returns (uint256 _total); function wasAccountChanged(address _address) external view returns (bool); function wasAccountCommitted(address _address) external view returns (bool); /************************************ * Public Functions: Storage Access * ************************************/ function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external; function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value); function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists); function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded); function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged); function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted); function incrementTotalUncommittedContractStorage() external; function getTotalUncommittedContractStorage() external view returns (uint256 _total); function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool); function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_DeployerWhitelist */ interface iOVM_DeployerWhitelist { /******************** * Public Functions * ********************/ function initialize(address _owner, bool _allowArbitraryDeployment) external; function getOwner() external returns (address _owner); function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external; function setOwner(address _newOwner) external; function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external; function enableArbitraryContractDeployment() external; function isDeployerAllowed(address _deployer) external returns (bool _allowed); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum EOASignatureType { EIP155_TRANSACTION, ETH_SIGNED_MESSAGE } enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct Account { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; address ethAddress; bool isFresh; } struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } struct EIP155Transaction { uint256 nonce; uint256 gasPrice; uint256 gasLimit; address to; uint256 value; bytes data; uint256 chainId; } /********************** * Internal Functions * **********************/ /** * Decodes an EOA transaction (i.e., native Ethereum RLP encoding). * @param _transaction Encoded EOA transaction. * @return Transaction decoded into a struct. */ function decodeEIP155Transaction( bytes memory _transaction, bool _isEthSignedMessage ) internal pure returns ( EIP155Transaction memory ) { if (_isEthSignedMessage) { ( uint256 _nonce, uint256 _gasLimit, uint256 _gasPrice, uint256 _chainId, address _to, bytes memory _data ) = abi.decode( _transaction, (uint256, uint256, uint256, uint256, address ,bytes) ); return EIP155Transaction({ nonce: _nonce, gasPrice: _gasPrice, gasLimit: _gasLimit, to: _to, value: 0, data: _data, chainId: _chainId }); } else { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_transaction); return EIP155Transaction({ nonce: Lib_RLPReader.readUint256(decoded[0]), gasPrice: Lib_RLPReader.readUint256(decoded[1]), gasLimit: Lib_RLPReader.readUint256(decoded[2]), to: Lib_RLPReader.readAddress(decoded[3]), value: Lib_RLPReader.readUint256(decoded[4]), data: Lib_RLPReader.readBytes(decoded[5]), chainId: Lib_RLPReader.readUint256(decoded[6]) }); } } /** * Decompresses a compressed EIP155 transaction. * @param _transaction Compressed EIP155 transaction bytes. * @return Transaction parsed into a struct. */ function decompressEIP155Transaction( bytes memory _transaction ) internal returns ( EIP155Transaction memory ) { return EIP155Transaction({ gasLimit: Lib_BytesUtils.toUint24(_transaction, 0), gasPrice: uint256(Lib_BytesUtils.toUint24(_transaction, 3)) * 1000000, nonce: Lib_BytesUtils.toUint24(_transaction, 6), to: Lib_BytesUtils.toAddress(_transaction, 9), data: Lib_BytesUtils.slice(_transaction, 29), chainId: Lib_SafeExecutionManagerWrapper.safeCHAINID(), value: 0 }); } /** * Encodes an EOA transaction back into the original transaction. * @param _transaction EIP155transaction to encode. * @param _isEthSignedMessage Whether or not this was an eth signed message. * @return Encoded transaction. */ function encodeEIP155Transaction( EIP155Transaction memory _transaction, bool _isEthSignedMessage ) internal pure returns ( bytes memory ) { if (_isEthSignedMessage) { return abi.encode( _transaction.nonce, _transaction.gasLimit, _transaction.gasPrice, _transaction.chainId, _transaction.to, _transaction.data ); } else { bytes[] memory raw = new bytes[](9); raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce); raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice); raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit); if (_transaction.to == address(0)) { raw[3] = Lib_RLPWriter.writeBytes(''); } else { raw[3] = Lib_RLPWriter.writeAddress(_transaction.to); } raw[4] = Lib_RLPWriter.writeUint(0); raw[5] = Lib_RLPWriter.writeBytes(_transaction.data); raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId); raw[7] = Lib_RLPWriter.writeBytes(bytes('')); raw[8] = Lib_RLPWriter.writeBytes(bytes('')); return Lib_RLPWriter.writeList(raw); } } /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction( Transaction memory _transaction ) internal pure returns ( bytes memory ) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction( Transaction memory _transaction ) internal pure returns ( bytes32 ) { return keccak256(encodeTransaction(_transaction)); } /** * Converts an OVM account to an EVM account. * @param _in OVM account to convert. * @return Converted EVM account. */ function toEVMAccount( Account memory _in ) internal pure returns ( EVMAccount memory ) { return EVMAccount({ nonce: _in.nonce, balance: _in.balance, storageRoot: _in.storageRoot, codeHash: _in.codeHash }); } /** * @notice RLP-encodes an account state struct. * @param _account Account state struct. * @return RLP-encoded account state. */ function encodeEVMAccount( EVMAccount memory _account ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](4); // Unfortunately we can't create this array outright because // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning // index-by-index circumvents this issue. raw[0] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.nonce) ) ); raw[1] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.balance) ) ); raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot)); raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash)); return Lib_RLPWriter.writeList(raw); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount( bytes memory _encoded ) internal pure returns ( EVMAccount memory ) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { Ownable } from "./Lib_Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string _name, address _newAddress ); /******************************************* * Contract Variables: Internal Accounting * *******************************************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ function setAddress( string memory _name, address _address ) public onlyOwner { emit AddressSet(_name, _address); addresses[_getNameHash(_name)] = _address; } function getAddress( string memory _name ) public view returns (address) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ function _getNameHash( string memory _name ) internal pure returns ( bytes32 _hash ) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /******************************************* * Contract Variables: Contract References * *******************************************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ function resolve( string memory _name ) public view returns ( address _contract ) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Ownable * @dev Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol */ abstract contract Ownable { /************* * Variables * *************/ address public owner; /********** * Events * **********/ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /*************** * Constructor * ***************/ constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require( owner == msg.sender, "Ownable: caller is not the owner" ); _; } /******************** * Public Functions * ********************/ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } function transferOwnership(address _newOwner) public virtual onlyOwner { require( _newOwner != address(0), "Ownable: new owner cannot be the zero address" ); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 constant internal MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem( bytes memory _in ) internal pure returns ( RLPItem memory ) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( RLPItem memory _in ) internal pure returns ( RLPItem[] memory ) { ( uint256 listOffset, , RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value." ); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require( itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length." ); ( uint256 itemOffset, uint256 itemLength, ) = _decodeLength(RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( bytes memory _in ) internal pure returns ( RLPItem[] memory ) { return readList( toRLPItem(_in) ); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value." ); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( bytes memory _in ) internal pure returns ( bytes memory ) { return readBytes( toRLPItem(_in) ); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( RLPItem memory _in ) internal pure returns ( string memory ) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( bytes memory _in ) internal pure returns ( string memory ) { return readString( toRLPItem(_in) ); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( RLPItem memory _in ) internal pure returns ( bytes32 ) { require( _in.length <= 33, "Invalid RLP bytes32 value." ); ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value." ); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( bytes memory _in ) internal pure returns ( bytes32 ) { return readBytes32( toRLPItem(_in) ); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( RLPItem memory _in ) internal pure returns ( uint256 ) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( bytes memory _in ) internal pure returns ( uint256 ) { return readUint256( toRLPItem(_in) ); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( RLPItem memory _in ) internal pure returns ( bool ) { require( _in.length == 1, "Invalid RLP boolean value." ); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require( out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1" ); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( bytes memory _in ) internal pure returns ( bool ) { return readBool( toRLPItem(_in) ); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( RLPItem memory _in ) internal pure returns ( address ) { if (_in.length == 1) { return address(0); } require( _in.length == 21, "Invalid RLP address value." ); return address(readUint256(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( bytes memory _in ) internal pure returns ( address ) { return readAddress( toRLPItem(_in) ); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength( RLPItem memory _in ) private pure returns ( uint256, uint256, RLPItemType ) { require( _in.length > 0, "RLP item cannot be null." ); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require( _in.length > strLen, "Invalid RLP short string." ); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require( _in.length > lenOfStrLen, "Invalid RLP long string length." ); uint256 strLen; assembly { // Pick out the string length. strLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)) ) } require( _in.length > lenOfStrLen + strLen, "Invalid RLP long string." ); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require( _in.length > listLen, "Invalid RLP short list." ); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require( _in.length > lenOfListLen, "Invalid RLP long list length." ); uint256 listLen; assembly { // Pick out the list length. listLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)) ) } require( _in.length > lenOfListLen + listLen, "Invalid RLP long list." ); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns ( bytes memory ) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy( RLPItem memory _in ) private pure returns ( bytes memory ) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return _out The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory _out ) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return _out The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory _out ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return _out The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory _out ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return _out The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return _out The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return _out The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory _out ) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return _encoded RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory _encoded ) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = byte(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55); for(i = 1; i <= lenLen; i++) { encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return _binary RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory _binary ) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return _flattened The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory _flattened ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20)} _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool( bytes32 _in ) internal pure returns ( bool ) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool( bool _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress( bytes32 _in ) internal pure returns ( address ) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress( address _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in)); } /** * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value. * @param _in Input bytes32 value. * @return Bytes32 without any leading zeros. */ function removeLeadingZeros( bytes32 _in ) internal pure returns ( bytes memory ) { bytes memory out; assembly { // Figure out how many leading zero bytes to remove. let shift := 0 for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } { shift := add(shift, 1) } // Reserve some space for our output and fix the free memory pointer. out := mload(0x40) mstore(0x40, add(out, 0x40)) // Shift the value and store it into the output bytes. mstore(add(out, 0x20), shl(mul(shift, 8), _in)) // Store the new size (with leading zero bytes removed) in the output byte size. mstore(out, sub(32, shift)) } return out; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice( bytes memory _bytes, uint256 _start ) internal pure returns (bytes memory) { if (_bytes.length - _start == 0) { return bytes(''); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32PadLeft( bytes memory _bytes ) internal pure returns (bytes32) { bytes32 ret; uint256 len = _bytes.length <= 32 ? _bytes.length : 32; assembly { ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32))) } return ret; } function toBytes32( bytes memory _bytes ) internal pure returns (bytes32) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes } function toUint256( bytes memory _bytes ) internal pure returns (uint256) { return uint256(toBytes32(_bytes)); } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, "toUint24_overflow"); require(_bytes.length >= _start + 3 , "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, "toAddress_overflow"); require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toNibbles( bytes memory _bytes ) internal pure returns (bytes memory) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles( bytes memory _bytes ) internal pure returns (bytes memory) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal( bytes memory _bytes, bytes memory _other ) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_ECDSAUtils */ library Lib_ECDSAUtils { /************************************** * Internal Functions: ECDSA Recovery * **************************************/ /** * Recovers a signed address given a message and signature. * @param _message Message that was originally signed. * @param _isEthSignedMessage Whether or not the user used the `Ethereum Signed Message` prefix. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. * @return _sender Signer address. */ function recover( bytes memory _message, bool _isEthSignedMessage, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns ( address _sender ) { bytes32 messageHash = getMessageHash(_message, _isEthSignedMessage); return ecrecover( messageHash, _v + 27, _r, _s ); } function getMessageHash( bytes memory _message, bool _isEthSignedMessage ) internal pure returns (bytes32) { if (_isEthSignedMessage) { return getEthSignedMessageHash(_message); } return getNativeMessageHash(_message); } /************************************* * Private Functions: ECDSA Recovery * *************************************/ /** * Gets the native message hash (simple keccak256) for a message. * @param _message Message to hash. * @return _messageHash Native message hash. */ function getNativeMessageHash( bytes memory _message ) private pure returns ( bytes32 _messageHash ) { return keccak256(_message); } /** * Gets the hash of a message with the `Ethereum Signed Message` prefix. * @param _message Message to hash. * @return _messageHash Prefixed message hash. */ function getEthSignedMessageHash( bytes memory _message ) private pure returns ( bytes32 _messageHash ) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 messageHash = keccak256(_message); return keccak256(abi.encodePacked(prefix, messageHash)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_ErrorUtils */ library Lib_ErrorUtils { /********************** * Internal Functions * **********************/ /** * Encodes an error string into raw solidity-style revert data. * (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))")) * Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)#panic-via-assert-and-error-via-require * @param _reason Reason for the reversion. * @return Standard solidity revert data for the given reason. */ function encodeRevertString( string memory _reason ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "Error(string)", _reason ); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol"; /** * @title Lib_EthUtils */ library Lib_EthUtils { /*********************************** * Internal Functions: Code Access * ***********************************/ /** * Gets the code for a given address. * @param _address Address to get code for. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return _code Code read from the contract. */ function getCode( address _address, uint256 _offset, uint256 _length ) internal view returns ( bytes memory _code ) { assembly { _code := mload(0x40) mstore(0x40, add(_code, add(_length, 0x20))) mstore(_code, _length) extcodecopy(_address, add(_code, 0x20), _offset, _length) } return _code; } /** * Gets the full code for a given address. * @param _address Address to get code for. * @return _code Full code of the contract. */ function getCode( address _address ) internal view returns ( bytes memory _code ) { return getCode( _address, 0, getCodeSize(_address) ); } /** * Gets the size of a contract's code in bytes. * @param _address Address to get code size for. * @return _codeSize Size of the contract's code in bytes. */ function getCodeSize( address _address ) internal view returns ( uint256 _codeSize ) { assembly { _codeSize := extcodesize(_address) } return _codeSize; } /** * Gets the hash of a contract's code. * @param _address Address to get a code hash for. * @return _codeHash Hash of the contract's code. */ function getCodeHash( address _address ) internal view returns ( bytes32 _codeHash ) { assembly { _codeHash := extcodehash(_address) } return _codeHash; } /***************************************** * Internal Functions: Contract Creation * *****************************************/ /** * Creates a contract with some given initialization code. * @param _code Contract initialization code. * @return _created Address of the created contract. */ function createContract( bytes memory _code ) internal returns ( address _created ) { assembly { _created := create( 0, add(_code, 0x20), mload(_code) ) } return _created; } /** * Computes the address that would be generated by CREATE. * @param _creator Address creating the contract. * @param _nonce Creator's nonce. * @return _address Address to be generated by CREATE. */ function getAddressForCREATE( address _creator, uint256 _nonce ) internal pure returns ( address _address ) { bytes[] memory encoded = new bytes[](2); encoded[0] = Lib_RLPWriter.writeAddress(_creator); encoded[1] = Lib_RLPWriter.writeUint(_nonce); bytes memory encodedList = Lib_RLPWriter.writeList(encoded); return Lib_Bytes32Utils.toAddress(keccak256(encodedList)); } /** * Computes the address that would be generated by CREATE2. * @param _creator Address creating the contract. * @param _bytecode Bytecode of the contract to be created. * @param _salt 32 byte salt value mixed into the hash. * @return _address Address to be generated by CREATE2. */ function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) internal pure returns (address _address) { bytes32 hashedData = keccak256(abi.encodePacked( byte(0xff), _creator, _salt, keccak256(_bytecode) )); return Lib_Bytes32Utils.toAddress(hashedData); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol"; /** * @title Lib_SafeExecutionManagerWrapper * @dev The Safe Execution Manager Wrapper provides functions which facilitate writing OVM safe * code using the standard solidity compiler, by routing all its operations through the Execution * Manager. * * Compiler used: solc * Runtime target: OVM */ library Lib_SafeExecutionManagerWrapper { /********************** * Internal Functions * **********************/ /** * Performs a safe ovmCALL. * @param _gasLimit Gas limit for the call. * @param _target Address to call. * @param _calldata Data to send to the call. * @return _success Whether or not the call reverted. * @return _returndata Data returned by the call. */ function safeCALL( uint256 _gasLimit, address _target, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCALL(uint256,address,bytes)", _gasLimit, _target, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Performs a safe ovmDELEGATECALL. * @param _gasLimit Gas limit for the call. * @param _target Address to call. * @param _calldata Data to send to the call. * @return _success Whether or not the call reverted. * @return _returndata Data returned by the call. */ function safeDELEGATECALL( uint256 _gasLimit, address _target, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmDELEGATECALL(uint256,address,bytes)", _gasLimit, _target, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Performs a safe ovmCREATE call. * @param _gasLimit Gas limit for the creation. * @param _bytecode Code for the new contract. * @return _contract Address of the created contract. */ function safeCREATE( uint256 _gasLimit, bytes memory _bytecode ) internal returns ( address, bytes memory ) { bytes memory returndata = _safeExecutionManagerInteraction( _gasLimit, abi.encodeWithSignature( "ovmCREATE(bytes)", _bytecode ) ); return abi.decode(returndata, (address, bytes)); } /** * Performs a safe ovmEXTCODESIZE call. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function safeEXTCODESIZE( address _contract ) internal returns ( uint256 _EXTCODESIZE ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmEXTCODESIZE(address)", _contract ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmCHAINID call. * @return _CHAINID Result of calling ovmCHAINID. */ function safeCHAINID() internal returns ( uint256 _CHAINID ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCHAINID()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmCALLER call. * @return _CALLER Result of calling ovmCALLER. */ function safeCALLER() internal returns ( address _CALLER ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCALLER()" ) ); return abi.decode(returndata, (address)); } /** * Performs a safe ovmADDRESS call. * @return _ADDRESS Result of calling ovmADDRESS. */ function safeADDRESS() internal returns ( address _ADDRESS ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmADDRESS()" ) ); return abi.decode(returndata, (address)); } /** * Performs a safe ovmGETNONCE call. * @return _nonce Result of calling ovmGETNONCE. */ function safeGETNONCE() internal returns ( uint256 _nonce ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmGETNONCE()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmINCREMENTNONCE call. */ function safeINCREMENTNONCE() internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); } /** * Performs a safe ovmCREATEEOA call. * @param _messageHash Message hash which was signed by EOA * @param _v v value of signature (0 or 1) * @param _r r value of signature * @param _s s value of signature */ function safeCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); } /** * Performs a safe REVERT. * @param _reason String revert reason to pass along with the REVERT. */ function safeREVERT( string memory _reason ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmREVERT(bytes)", Lib_ErrorUtils.encodeRevertString( _reason ) ) ); } /** * Performs a safe "require". * @param _condition Boolean condition that must be true or will revert. * @param _reason String revert reason to pass along with the REVERT. */ function safeREQUIRE( bool _condition, string memory _reason ) internal { if (!_condition) { safeREVERT( _reason ); } } /** * Performs a safe ovmSLOAD call. */ function safeSLOAD( bytes32 _key ) internal returns ( bytes32 ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmSLOAD(bytes32)", _key ) ); return abi.decode(returndata, (bytes32)); } /** * Performs a safe ovmSSTORE call. */ function safeSSTORE( bytes32 _key, bytes32 _value ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmSSTORE(bytes32,bytes32)", _key, _value ) ); } /********************* * Private Functions * *********************/ /** * Performs an ovm interaction and the necessary safety checks. * @param _gasLimit Gas limit for the interaction. * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash). * @return _returndata Data sent back by the OVM_ExecutionManager. */ function _safeExecutionManagerInteraction( uint256 _gasLimit, bytes memory _calldata ) private returns ( bytes memory _returndata ) { address ovmExecutionManager = msg.sender; ( bool success, bytes memory returndata ) = ovmExecutionManager.call{gas: _gasLimit}(_calldata); if (success == false) { assembly { revert(add(returndata, 0x20), mload(returndata)) } } else if (returndata.length == 1) { assembly { return(0, 1) } } else { return returndata; } } function _safeExecutionManagerInteraction( bytes memory _calldata ) private returns ( bytes memory _returndata ) { return _safeExecutionManagerInteraction( gasleft(), _calldata ); } } // SPDX-License-Identifier: MIT // Pulled from @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_SafeExecutionManagerWrapper } from "./Lib_SafeExecutionManagerWrapper.sol"; /** * @title Lib_SafeMathWrapper */ /** * @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 Lib_SafeMathWrapper { /** * @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 returns (uint256) { uint256 c = a + b; Lib_SafeExecutionManagerWrapper.safeREQUIRE(c >= a, "Lib_SafeMathWrapper: 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 returns (uint256) { return sub(a, b, "Lib_SafeMathWrapper: 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 returns (uint256) { Lib_SafeExecutionManagerWrapper.safeREQUIRE(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 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; Lib_SafeExecutionManagerWrapper.safeREQUIRE(c / a == b, "Lib_SafeMathWrapper: 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 returns (uint256) { return div(a, b, "Lib_SafeMathWrapper: 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 returns (uint256) { Lib_SafeExecutionManagerWrapper.safeREQUIRE(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 returns (uint256) { return mod(a, b, "Lib_SafeMathWrapper: 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 returns (uint256) { Lib_SafeExecutionManagerWrapper.safeREQUIRE(b != 0, errorMessage); return a % b; } }
Overrides TIMESTAMP. return _TIMESTAMP Value of the TIMESTAMP within the transaction context./
function ovmTIMESTAMP() override public view returns ( uint256 _TIMESTAMP ) { return transactionContext.ovmTIMESTAMP; }
10,429,510
// SPDX-License-Identifier: MIT pragma solidity ^0.4.24; contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; // address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } // function transferOwnership(address _newOwner) public onlyOwner { // newOwner = _newOwner; // } // function acceptOwnership() public { // require(msg.sender == newOwner); // emit OwnershipTransferred(owner, newOwner); // owner = newOwner; // newOwner = address(0); // } } contract DATAP is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public totalSupply; uint public rate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "DATAP"; name = "DataX Protocol"; decimals = 18; totalSupply = 1000000000 * 10 ** uint256(decimals); rate = 203; balances[owner] = totalSupply; emit Transfer(address(0), owner, totalSupply); } function changeRate(uint newRate) public onlyOwner { require(newRate > 0); rate = newRate; } function totalSupply() public view returns (uint) { return totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } modifier validTo(address to) { require(to != address(0)); require(to != address(this)); _; } function transferInternal(address from, address to, uint tokens) internal { balances[from] = safeSub(balances[from], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); } function transfer(address to, uint tokens) public validTo(to) returns (bool success) { transferInternal(msg.sender, to, 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 validTo(to) returns (bool success) { allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); transferInternal(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if (approve(spender, tokens)) { ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function () public payable { uint tokens; tokens = safeMul(msg.value, rate); balances[owner] = safeSub(balances[owner], tokens); balances[msg.sender] = safeAdd(balances[msg.sender], tokens); emit Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ // function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { // return ERC20Interface(tokenAddress).transfer(owner, tokens); // } }
------------------------------------------------------------------------ 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) { if (approve(spender, tokens)) { ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } }
1,253,166
pragma solidity >=0.4.21 <0.6.0; import "contracts/CreateAddress.sol"; import "contracts/Cloning.sol"; contract Ancestry is CreateAddress, Cloning { // The root of the family tree. address public PROGENITOR; uint256[] public BIRTH_CERTIFICATE; uint256 public next_nonce; modifier onlyRelatives(uint256[] memory birthCerificate) { require(descends(PROGENITOR, msg.sender, birthCerificate), "NOT_RELATED"); _; } // TODO: only_ancestors, only_parents, only_children, only_offspring, only_sibblings constructor() public { uint256[] memory genesis = new uint256[](0); initializeAncestry(address(0), genesis); } function initializeAncestry( address progenitor, uint256[] memory birthCerificate ) public { require(PROGENITOR == address(0x0), "ANCESTRY_ALREADY_INITIALIZED"); if (progenitor == address(0)) { progenitor = address(this); } require(descends(progenitor, address(this), birthCerificate), "INVALID_BIRTH_CERTIFICATE"); PROGENITOR = progenitor; BIRTH_CERTIFICATE = birthCerificate; // Constract child nonces start at 1 next_nonce = 1; } /// Check if a given contract is a sibbling /// @param progenitor The root of the family tree. /// @param descendant The constract address to check for membership in the family tree. /// @param birthCertificate Claimed proof of ancenstry. function descends( address progenitor, address descendant, uint256[] memory birthCertificate ) public pure returns (bool) { address relative = progenitor; for (uint256 i = 0; i < birthCertificate.length; ++i) { relative = create1(relative, birthCertificate[i]); } return relative == descendant; } /// Returns a clone of the current contract. All state is initialized /// zero except for the ancestry information. function procreate() public returns (Ancestry child) { child = Ancestry(spawn()); child.initializeAncestry( PROGENITOR, issueBirthCertificate() ); } /// Issues a birth certificate for the next child contract. /// NOTE: The birth certificate must be used in the next CREATE. /// NOTE: A birth certificate must be requested for each CREATE. function issueBirthCertificate() private returns (uint256[] memory birthCertificate) { birthCertificate = new uint256[](BIRTH_CERTIFICATE.length + 1); // Copy over exsisting certificate for(uint256 i = 0; i < BIRTH_CERTIFICATE.length; ++i) { birthCertificate[i] = BIRTH_CERTIFICATE[i]; } // Append new entry birthCertificate[BIRTH_CERTIFICATE.length] = next_nonce; // Increment CREATE nonce next_nonce += 1; } }
Returns a clone of the current contract. All state is initialized zero except for the ancestry information.
function procreate() public returns (Ancestry child) { child = Ancestry(spawn()); child.initializeAncestry( PROGENITOR, issueBirthCertificate() ); }
12,952,117
pragma solidity ^0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract OniRobots is ERC721, Ownable { using Counters for Counters.Counter; // Map the number of tokens per robotId mapping(uint8 => uint256) public robotCount; // Map the number of tokens burnt per robotId mapping(uint8 => uint256) public robotBurnCount; // Used for generating the tokenId of new NFT minted Counters.Counter private _tokenIds; // Map the robotId for each tokenId mapping(uint256 => uint8) private robotIds; // Map the robotName for a tokenId mapping(uint8 => string) private robotNames; constructor(string memory _baseURI) public ERC721("Oniswap Robots", "OR") { _setBaseURI(_baseURI); } /** * @dev Get robotId for a specific tokenId. */ function getRobotId(uint256 _tokenId) external view returns (uint8) { return robotIds[_tokenId]; } /** * @dev Get the associated robotName for a specific robotId. */ function getRobotName(uint8 _robotId) external view returns (string memory) { return robotNames[_robotId]; } /** * @dev Get the associated robotName for a unique tokenId. */ function getRobotNameOfTokenId(uint256 _tokenId) external view returns (string memory) { uint8 robotId = robotIds[_tokenId]; return robotNames[robotId]; } /** * @dev Mint NFTs. Only the owner can call it. */ function mint( address _to, string calldata _tokenURI, uint8 _robotId ) external onlyOwner returns (uint256) { uint256 newId = _tokenIds.current(); _tokenIds.increment(); robotIds[newId] = _robotId; robotCount[_robotId] = robotCount[_robotId].add(1); _mint(_to, newId); _setTokenURI(newId, _tokenURI); return newId; } /** * @dev Set a unique name for each robotId. It is supposed to be called once. */ function setRobotName(uint8 _robotId, string calldata _name) external onlyOwner { robotNames[_robotId] = _name; } /** * @dev Burn a NFT token. Callable by owner only. */ function burn(uint256 _tokenId) external onlyOwner { uint8 robotIdBurnt = robotIds[_tokenId]; robotCount[robotIdBurnt] = robotCount[robotIdBurnt].sub(1); robotBurnCount[robotIdBurnt] = robotBurnCount[robotIdBurnt].add(1); _burn(_tokenId); } }
Burn a NFT token. Callable by owner only./
function burn(uint256 _tokenId) external onlyOwner { uint8 robotIdBurnt = robotIds[_tokenId]; robotCount[robotIdBurnt] = robotCount[robotIdBurnt].sub(1); robotBurnCount[robotIdBurnt] = robotBurnCount[robotIdBurnt].add(1); _burn(_tokenId); }
12,771,617
pragma solidity ^0.4.24; import "./NFTokenMetadata.sol"; contract CustomToken is NFTokenMetadata { address public owner; constructor(string _name, string _symbol) public { owner = msg.sender; nftName = _name; nftSymbol = _symbol; } // owner can mint arbitrary tokens function mint(address _owner, uint256 _id, string _uri) external { require(msg.sender == owner); super._mint(_owner, _id); super._setTokenUri(_id, _uri); } // owner can burn arbitrary tokens function burn(address _owner, uint256 _tokenId) external { require(msg.sender == owner); super._burn(_owner, _tokenId); } // allow change of ownership (simple version without events) function changeOwner(address _owner) external { require(msg.sender == owner); owner = _owner; } }
owner can burn arbitrary tokens
function burn(address _owner, uint256 _tokenId) external { require(msg.sender == owner); super._burn(_owner, _tokenId); }
1,006,955
pragma solidity 0.5.3; import "./oz/SafeMath.sol"; import "./oz/IERC20.sol"; import "./GuildBank.sol"; contract Moloch { using SafeMath for uint256; // **************** // GLOBAL CONSTANTS // **************** uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public emergencyExitWait; // default = 35 periods (7 days) - if proposal has not been processed after this time, its logic will be skipped uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal uint256 public summoningTime; // needed to determine the current period IERC20 public depositToken; // reference to the deposit token GuildBank public guildBank; // guild bank contract reference // HARD-CODED LIMITS // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound uint256 constant MAX_NUMBER_OF_SHARES = 10**18; // maximum number of shares that can be minted // *************** // EVENTS // *************** event SubmitProposal(uint256 proposalIndex, address indexed delegateKey, address indexed memberAddress, address indexed applicant, uint256 tributeOffered, uint256 sharesRequested); event SubmitVote(uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote); event ProcessProposal(uint256 indexed proposalIndex, address indexed applicant, address indexed memberAddress, uint256 tributeOffered, uint256 sharesRequested, bool didPass); event Ragequit(address indexed memberAddress, uint256 sharesToBurn); event CancelProposal(uint256 indexed proposalIndex, address applicantAddress); event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey); event SummonComplete(address indexed summoner, uint256 shares); // ******************* // INTERNAL ACCOUNTING // ******************* uint256 public proposalCount = 0; // total proposals submitted uint256 public totalShares = 0; // total shares across all members uint256 public totalSharesRequested = 0; // total shares that have been requested in unprocessed proposals enum Vote { Null, // default value, counted as abstention Yes, No } struct Member { address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated uint256 shares; // the # of shares assigned to this member bool exists; // always true once a member has been created uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals address proposer; // whoever submitted the proposal (can be non-member) address sponsor; // the member who sponsored the proposal uint256 sharesRequested; // the # of shares the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute IERC20 tributeToken; // token being offered as tribute uint256 paymentRequested; // the payments requested for each applicant IERC20 paymentToken; // token to send payment in uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] // 0. sponsored - true only if the proposal has been submitted by a member // 1. processed - true only if the proposal has been processed // 2. didPass - true only if the proposal passed // 3. cancelled - true only if the proposer called cancelProposal before a member sponsored the proposal // 4. whitelist - true only if this is a whitelist proposal, NOTE - tributeToken is target of whitelist // 5. guildkick - true only if this is a guild kick proposal, NOTE - applicant is target of guild kick string details; // proposal details - could be IPFS hash, plaintext, or JSON uint256 maxTotalSharesAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal mapping (address => Vote) votesByMember; // the votes on this proposal by each member } mapping (address => bool) public tokenWhitelist; IERC20[] public approvedTokens; mapping (address => bool) public proposedToWhitelist; // true if a token has been proposed to the whitelist (to avoid duplicate whitelist proposals) mapping (address => bool) public proposedToKick; // true if a member has been proposed to be kicked (to avoid duplicate guild kick proposals) mapping (address => Member) public members; mapping (address => address) public memberAddressByDelegateKey; // proposals by ID mapping (uint256 => Proposal) public proposals; // the queue of proposals (only store a reference by the proposal id) uint256[] public proposalQueue; // ********* // MODIFIERS // ********* modifier onlyMember { require(members[msg.sender].shares > 0, "Moloch::onlyMember - not a member"); _; } modifier onlyDelegate { require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "Moloch::onlyDelegate - not a delegate"); _; } // ********* // FUNCTIONS // ********* constructor( address summoner, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _emergencyExitWait, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward ) public { require(summoner != address(0), "Moloch::constructor - summoner cannot be 0"); require(_periodDuration > 0, "Moloch::constructor - _periodDuration cannot be 0"); require(_votingPeriodLength > 0, "Moloch::constructor - _votingPeriodLength cannot be 0"); require(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "Moloch::constructor - _votingPeriodLength exceeds limit"); require(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "Moloch::constructor - _gracePeriodLength exceeds limit"); require(_emergencyExitWait > 0, "Moloch::constructor - _emergencyExitWait cannot be 0"); require(_dilutionBound > 0, "Moloch::constructor - _dilutionBound cannot be 0"); require(_dilutionBound <= MAX_DILUTION_BOUND, "Moloch::constructor - _dilutionBound exceeds limit"); require(_approvedTokens.length > 0, "Moloch::constructor - need at least one approved token"); require(_proposalDeposit >= _processingReward, "Moloch::constructor - _proposalDeposit cannot be smaller than _processingReward"); // first approved token is the deposit token depositToken = IERC20(_approvedTokens[0]); for (uint256 i=0; i < _approvedTokens.length; i++) { require(_approvedTokens[i] != address(0), "Moloch::constructor - _approvedToken cannot be 0"); require(!tokenWhitelist[_approvedTokens[i]], "Moloch::constructor - duplicate approved token"); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(IERC20(_approvedTokens[i])); } guildBank = new GuildBank(); periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; emergencyExitWait = _emergencyExitWait; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; summoningTime = now; members[summoner] = Member(summoner, 1, true, 0); memberAddressByDelegateKey[summoner] = summoner; totalShares = 1; emit SummonComplete(summoner, 1); } // ****************** // PROPOSAL FUNCTIONS // ****************** function submitProposal( address applicant, uint256 sharesRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details ) public { require(tokenWhitelist[tributeToken], "Moloch::submitProposal - tributeToken is not whitelisted"); require(tokenWhitelist[paymentToken], "Moloch::submitProposal - payment is not whitelisted"); require(applicant != address(0), "Moloch::submitProposal - applicant cannot be 0"); // collect tribute from applicant and store it in the Moloch until the proposal is processed require(IERC20(tributeToken).transferFrom(msg.sender, address(this), tributeOffered), "Moloch::submitProposal - tribute token transfer failed"); bool[6] memory flags; // create proposal... Proposal memory proposal = Proposal({ applicant: applicant, proposer: msg.sender, sponsor: address(0), sharesRequested: sharesRequested, tributeOffered: tributeOffered, tributeToken: IERC20(tributeToken), paymentRequested: paymentRequested, paymentToken: IERC20(paymentToken), startingPeriod: 0, yesVotes: 0, noVotes: 0, flags: flags, details: details, maxTotalSharesAtYesVote: 0 }); proposals[proposalCount] = proposal; // save proposal by its id proposalCount += 1; // increment proposal counter // uint256 proposalIndex = proposalQueue.length.sub(1); // TODO emit SubmitProposal(proposalIndex, msg.sender, memberAddress, applicant, tributeOffered, sharesRequested); } function submitWhitelistProposal(address tokenToWhitelist, string memory details) public { require(tokenToWhitelist != address(0), "Moloch::submitWhitelistProposal - must provide token address"); require(!tokenWhitelist[tokenToWhitelist], "Moloch::submitWhitelistProposal - can't already have whitelisted the token"); bool[6] memory flags; flags[4] = true; // whitelist proposal = true // create proposal ... Proposal memory proposal = Proposal({ applicant: address(0), proposer: msg.sender, sponsor: address(0), sharesRequested: 0, tributeOffered: 0, tributeToken: IERC20(tokenToWhitelist), // tributeToken = tokenToWhitelist paymentRequested: 0, paymentToken: IERC20(address(0)), startingPeriod: 0, yesVotes: 0, noVotes: 0, flags: flags, details: details, maxTotalSharesAtYesVote: 0 }); proposals[proposalCount] = proposal; // save proposal by its id proposalCount += 1; // increment proposal counter // uint256 proposalIndex = proposalQueue.length.sub(1); // TODO emit SubmitProposal(proposalIndex, msg.sender, memberAddress, applicant, tributeOffered, sharesRequested); } function submitGuildKickProposal(address memberToKick, string memory details) public { require(members[memberToKick].shares > 0, "Moloch::submitGuildKickProposal - member must have at least one share"); bool[6] memory flags; flags[5] = true; // guild kick proposal = true // create proposal ... Proposal memory proposal = Proposal({ applicant: memberToKick, // applicant = memberToKick proposer: msg.sender, sponsor: address(0), sharesRequested: 0, tributeOffered: 0, tributeToken: IERC20(address(0)), paymentRequested: 0, paymentToken: IERC20(address(0)), startingPeriod: 0, yesVotes: 0, noVotes: 0, flags: flags, details: details, maxTotalSharesAtYesVote: 0 }); proposals[proposalCount] = proposal; // save proposal by its id proposalCount += 1; // increment proposal counter // uint256 proposalIndex = proposalQueue.length.sub(1); // TODO emit SubmitProposal(proposalIndex, msg.sender, memberAddress, applicant, tributeOffered, sharesRequested); } function sponsorProposal(uint256 proposalId) public onlyDelegate { // collect proposal deposit from proposer and store it in the Moloch until the proposal is processed require(depositToken.transferFrom(msg.sender, address(this), proposalDeposit), "Moloch::submitProposal - proposal deposit token transfer failed"); Proposal memory proposal = proposals[proposalId]; require(!proposal.flags[0], "Moloch::sponsorProposal - proposal has already been sponsored"); require(!proposal.flags[3], "Moloch::sponsorProposal - proposal has been cancelled"); // token whitelist proposal if (proposal.flags[4]) { require(!proposedToWhitelist[address(proposal.tributeToken)]); // already an active proposal to whitelist this token proposedToWhitelist[address(proposal.tributeToken)] = true; // gkick proposal } else if (proposal.flags[5]) { require(!proposedToKick[proposal.applicant]); // already an active proposal to kick this member proposedToKick[proposal.applicant] = true; // standard proposal } else { // Make sure we won't run into overflows when doing calculations with shares. // Note that totalShares + totalSharesRequested + sharesRequested is an upper bound // on the number of shares that can exist until this proposal has been processed. require(totalShares.add(totalSharesRequested).add(proposal.sharesRequested) <= MAX_NUMBER_OF_SHARES, "Moloch::submitProposal - too many shares requested"); totalSharesRequested = totalSharesRequested.add(proposal.sharesRequested); } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length.sub(1)]].startingPeriod ).add(1); proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; // ... and append it to the queue by its id proposalQueue.push(proposalId); // uint256 proposalIndex = proposalQueue.length.sub(1); // emit SponsorProposal(proposalId, proposalIndex, msg.sender, memberAddress, applicant, tributeOffered, sharesRequested); } function submitVote(uint256 proposalIndex, uint8 uintVote) public onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require(proposalIndex < proposalQueue.length, "Moloch::submitVote - proposal does not exist"); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(uintVote < 3, "Moloch::submitVote - uintVote must be less than 3"); Vote vote = Vote(uintVote); require(proposal.flags[0], "Moloch::submitVote - proposal has not been sponsored"); require(getCurrentPeriod() >= proposal.startingPeriod, "Moloch::submitVote - voting period has not started"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "Moloch::submitVote - proposal voting period has expired"); require(proposal.votesByMember[memberAddress] == Vote.Null, "Moloch::submitVote - member has already voted on this proposal"); require(vote == Vote.Yes || vote == Vote.No, "Moloch::submitVote - vote must be either Yes or No"); // store vote proposal.votesByMember[memberAddress] = vote; // count vote if (vote == Vote.Yes) { proposal.yesVotes = proposal.yesVotes.add(member.shares); // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totalShares > proposal.maxTotalSharesAtYesVote) { proposal.maxTotalSharesAtYesVote = totalShares; } } else if (vote == Vote.No) { proposal.noVotes = proposal.noVotes.add(member.shares); } emit SubmitVote(proposalIndex, msg.sender, memberAddress, uintVote); } function processProposal(uint256 proposalIndex) public { require(proposalIndex < proposalQueue.length, "Moloch::processProposal - proposal does not exist"); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength), "Moloch::processProposal - proposal is not ready to be processed"); require(proposal.flags[1] == false, "Moloch::processProposal - proposal has already been processed"); require(proposalIndex == 0 || proposals[proposalQueue[proposalIndex.sub(1)]].flags[1], "Moloch::processProposal - previous proposal must be processed"); proposal.flags[1] = true; totalSharesRequested = totalSharesRequested.sub(proposal.sharesRequested); bool didPass = proposal.yesVotes > proposal.noVotes; // If emergencyExitWait has passed from when this proposal *should* have been able to be processed, skip all effects bool emergencyProcessing = false; if (getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength).add(emergencyExitWait)) { emergencyProcessing = true; didPass = false; } // Make the proposal fail if the dilutionBound is exceeded if (totalShares.mul(dilutionBound) < proposal.maxTotalSharesAtYesVote) { didPass = false; } // Make sure there is enough tokens for payments, or auto-fail if (proposal.paymentRequested >= proposal.paymentToken.balanceOf(address(guildBank))) { didPass = false; } // PROPOSAL PASSED if (didPass) { proposal.flags[2] = true; // didPass = true // whitelist proposal passed, add token to whitelist if (proposal.flags[4]) { tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); // guild kick proposal passed, ragequit 100% of the member's shares // NOTE - if any approvedToken is broken gkicks will fail and get stuck here (until emergency processing) } else if (proposal.flags[5]) { _ragequit(members[proposal.applicant].shares, approvedTokens); // standard proposal passed, collect tribute, send payment, mint shares } else { // if the applicant is already a member, add to their existing shares if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested); // the applicant is a new member, create a new record for them } else { // if the applicant address is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[proposal.applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[proposal.applicant]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } // use applicant address as delegateKey by default members[proposal.applicant] = Member(proposal.applicant, proposal.sharesRequested, true, 0); memberAddressByDelegateKey[proposal.applicant] = proposal.applicant; } // mint new shares totalShares = totalShares.add(proposal.sharesRequested); // transfer tribute tokens to guild bank require( proposal.tributeToken.transfer(address(guildBank), proposal.tributeOffered), "Moloch::processProposal - token transfer to guild bank failed" ); // transfer payment tokens to applicant require( guildBank.withdrawToken(proposal.paymentToken, proposal.applicant, proposal.paymentRequested), "Moloch::processProposal - token payment to applicant failed" ); } // PROPOSAL FAILED } else { // Don't return applicant tokens if we are in emergency processing - likely the tokens are broken if (!emergencyProcessing) { // return all tokens to the proposer require( proposal.tributeToken.transfer(proposal.proposer, proposal.tributeOffered), "Moloch::processProposal - failing vote token transfer failed" ); } } // if token whitelist proposal, remove token from tokens proposed to whitelist if (proposal.flags[4]) { proposedToWhitelist[address(proposal.tributeToken)] = false; } // if guild kick proposal, remove member from list of members proposed to be kicked if (proposal.flags[5]) { proposedToKick[proposal.applicant] = false; } // send msg.sender the processingReward require( depositToken.transfer(msg.sender, processingReward), "Moloch::processProposal - failed to send processing reward to msg.sender" ); // return deposit to sponsor (subtract processing reward) require( depositToken.transfer(proposal.sponsor, proposalDeposit.sub(processingReward)), "Moloch::processProposal - failed to return proposal deposit to sponsor" ); // TODO emit ProcessProposal() } function ragequit(uint256 sharesToBurn) public onlyMember { _ragequit(sharesToBurn, approvedTokens); } function safeRagequit(uint256 sharesToBurn, IERC20[] memory tokenList) public onlyMember { // all tokens in tokenList must be in the tokenWhitelist for (uint256 i=0; i < tokenList.length; i++) { require(tokenWhitelist[address(tokenList[i])], "Moloch::safeRequit - token must be whitelisted"); // check token uniqueness - for every token address after the first, enforce ascending lexical order if (i > 0) { require(tokenList[i] > tokenList[i-1], "Moloch::safeRagequit - tokenList must be unique and in ascending order"); } } _ragequit(sharesToBurn, tokenList); } function _ragequit(uint256 sharesToBurn, IERC20[] memory approvedTokens) internal { uint256 initialTotalShares = totalShares; Member storage member = members[msg.sender]; require(member.shares >= sharesToBurn, "Moloch::ragequit - insufficient shares"); require(canRagequit(member.highestIndexYesVote), "Moloch::ragequit - cant ragequit until highest index proposal member voted YES on is processed"); // burn shares member.shares = member.shares.sub(sharesToBurn); totalShares = totalShares.sub(sharesToBurn); // instruct guildBank to transfer fair share of tokens to the ragequitter require( guildBank.withdraw(msg.sender, sharesToBurn, initialTotalShares, approvedTokens), "Moloch::ragequit - withdrawal of tokens from guildBank failed" ); emit Ragequit(msg.sender, sharesToBurn); } function cancelProposal(uint256 proposalId) public { Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[0], "Moloch::cancelProposal - proposal has already been sponsored"); require(msg.sender == proposal.proposer, "Moloch::cancelProposal - only the proposer can cancel"); proposal.flags[3] = true; // cancelled require( proposal.tributeToken.transfer(proposal.proposer, proposal.tributeOffered), "Moloch::processProposal - failed to return tribute to proposer" ); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) public onlyMember { require(newDelegateKey != address(0), "Moloch::updateDelegateKey - newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require(!members[newDelegateKey].exists, "Moloch::updateDelegateKey - cant overwrite existing members"); require(!members[memberAddressByDelegateKey[newDelegateKey]].exists, "Moloch::updateDelegateKey - cant overwrite existing delegate keys"); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // **************** // GETTER FUNCTIONS // **************** function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return now.sub(summoningTime).div(periodDuration); } function getProposalQueueLength() public view returns (uint256) { return proposalQueue.length; } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { require(highestIndexYesVote < proposalQueue.length, "Moloch::canRagequit - proposal does not exist"); return proposals[proposalQueue[highestIndexYesVote]].flags[1]; // processed } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= startingPeriod.add(votingPeriodLength); } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) { require(members[memberAddress].exists, "Moloch::getMemberProposalVote - member doesn't exist"); require(proposalIndex < proposalQueue.length, "Moloch::getMemberProposalVote - proposal doesn't exist"); return proposals[proposalQueue[proposalIndex]].votesByMember[memberAddress]; } }
If emergencyExitWait has passed from when this proposal should have been able to be processed, skip all effects Make the proposal fail if the dilutionBound is exceeded Make sure there is enough tokens for payments, or auto-fail PROPOSAL PASSED whitelist proposal passed, add token to whitelist guild kick proposal passed, ragequit 100% of the member's shares NOTE - if any approvedToken is broken gkicks will fail and get stuck here (until emergency processing) standard proposal passed, collect tribute, send payment, mint shares if the applicant is already a member, add to their existing shares the applicant is a new member, create a new record for them if the applicant address is already taken by a member's delegateKey, reset it to their member address Don't return applicant tokens if we are in emergency processing - likely the tokens are broken return all tokens to the proposer if token whitelist proposal, remove token from tokens proposed to whitelist if guild kick proposal, remove member from list of members proposed to be kicked
function processProposal(uint256 proposalIndex) public { require(proposalIndex < proposalQueue.length, "Moloch::processProposal - proposal does not exist"); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength), "Moloch::processProposal - proposal is not ready to be processed"); require(proposal.flags[1] == false, "Moloch::processProposal - proposal has already been processed"); require(proposalIndex == 0 || proposals[proposalQueue[proposalIndex.sub(1)]].flags[1], "Moloch::processProposal - previous proposal must be processed"); proposal.flags[1] = true; totalSharesRequested = totalSharesRequested.sub(proposal.sharesRequested); bool didPass = proposal.yesVotes > proposal.noVotes; bool emergencyProcessing = false; if (getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength).add(emergencyExitWait)) { emergencyProcessing = true; didPass = false; } if (totalShares.mul(dilutionBound) < proposal.maxTotalSharesAtYesVote) { didPass = false; } if (proposal.paymentRequested >= proposal.paymentToken.balanceOf(address(guildBank))) { didPass = false; } if (didPass) { if (proposal.flags[4]) { tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); _ragequit(members[proposal.applicant].shares, approvedTokens); if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested); if (members[memberAddressByDelegateKey[proposal.applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[proposal.applicant]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } memberAddressByDelegateKey[proposal.applicant] = proposal.applicant; } proposal.tributeToken.transfer(address(guildBank), proposal.tributeOffered), "Moloch::processProposal - token transfer to guild bank failed" ); guildBank.withdrawToken(proposal.paymentToken, proposal.applicant, proposal.paymentRequested), "Moloch::processProposal - token payment to applicant failed" ); } if (!emergencyProcessing) { require( proposal.tributeToken.transfer(proposal.proposer, proposal.tributeOffered), "Moloch::processProposal - failing vote token transfer failed" ); } } if (proposal.flags[4]) { proposedToWhitelist[address(proposal.tributeToken)] = false; } if (proposal.flags[5]) { proposedToKick[proposal.applicant] = false; } depositToken.transfer(msg.sender, processingReward), "Moloch::processProposal - failed to send processing reward to msg.sender" ); depositToken.transfer(proposal.sponsor, proposalDeposit.sub(processingReward)), "Moloch::processProposal - failed to return proposal deposit to sponsor" );
12,926,329
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeRouter} from "./BridgeRouter.sol"; import {IWeth} from "../../interfaces/bridge/IWeth.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; contract ETHHelper { // ============ Immutables ============ // wrapped Ether contract IWeth public immutable weth; // bridge router contract BridgeRouter public immutable bridge; // ============ Constructor ============ constructor(address _weth, address _bridge) { weth = IWeth(_weth); bridge = BridgeRouter(_bridge); IWeth(_weth).approve(_bridge, uint256(-1)); } // ============ External Functions ============ /** * @notice Sends ETH over the Optics Bridge. Sends to a full-width Optics * identifer on the other side. * @dev As with all bridges, improper use may result in loss of funds. * @param _domain The domain to send funds to. * @param _to The 32-byte identifier of the recipient */ function sendTo(uint32 _domain, bytes32 _to) public payable { weth.deposit{value: msg.value}(); bridge.send(address(weth), msg.value, _domain, _to); } /** * @notice Sends ETH over the Optics Bridge. Sends to the same address on * the other side. * @dev WARNING: This function should only be used when sending TO an * EVM-like domain. As with all bridges, improper use may result in loss of * funds. * @param _domain The domain to send funds to */ function send(uint32 _domain) external payable { sendTo(_domain, TypeCasts.addressToBytes32(msg.sender)); } /** * @notice Sends ETH over the Optics Bridge. Sends to a specified EVM * address on the other side. * @dev This function should only be used when sending TO an EVM-like * domain. As with all bridges, improper use may result in loss of funds * @param _domain The domain to send funds to. * @param _to The EVM address of the recipient */ function sendToEVMLike(uint32 _domain, address _to) external payable { sendTo(_domain, TypeCasts.addressToBytes32(_to)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {TokenRegistry} from "./TokenRegistry.sol"; import {Router} from "../Router.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {BridgeMessage} from "./BridgeMessage.sol"; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {Version0} from "@celo-org/optics-sol/contracts/Version0.sol"; import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title BridgeRouter */ contract BridgeRouter is Version0, Router, TokenRegistry { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; using SafeERC20 for IERC20; // ============ Constants ============ // 5 bps (0.05%) hardcoded fast liquidity fee. Can be changed by contract upgrade uint256 public constant PRE_FILL_FEE_NUMERATOR = 9995; uint256 public constant PRE_FILL_FEE_DENOMINATOR = 10000; // ============ Public Storage ============ // token transfer prefill ID => LP that pre-filled message to provide fast liquidity mapping(bytes32 => address) public liquidityProvider; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ======== Events ========= /** * @notice emitted when tokens are sent from this domain to another domain * @param token the address of the token contract * @param from the address sending tokens * @param toDomain the domain of the chain the tokens are being sent to * @param toId the bytes32 address of the recipient of the tokens * @param amount the amount of tokens sent */ event Send( address indexed token, address indexed from, uint32 indexed toDomain, bytes32 toId, uint256 amount ); // ======== Initializer ======== function initialize(address _tokenBeacon, address _xAppConnectionManager) public initializer { __TokenRegistry_initialize(_tokenBeacon); __XAppConnectionClient_initialize(_xAppConnectionManager); } // ======== External: Handle ========= /** * @notice Handles an incoming message * @param _origin The origin domain * @param _sender The sender address * @param _message The message */ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external override onlyReplica onlyRemoteRouter(_origin, _sender) { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId(); bytes29 _action = _msg.action(); // handle message based on the intended action if (_action.isTransfer()) { _handleTransfer(_tokenId, _action); } else if (_action.isDetails()) { _handleDetails(_tokenId, _action); } else if (_action.isRequestDetails()) { _handleRequestDetails(_origin, _sender, _tokenId); } else { require(false, "!valid action"); } } // ======== External: Request Token Details ========= /** * @notice Request updated token metadata from another chain * @dev This is only owner to prevent abuse and spam. Requesting details * should be done automatically on token instantiation * @param _domain The domain where that token is native * @param _id The token id on that domain */ function requestDetails(uint32 _domain, bytes32 _id) external onlyOwner { bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); _requestDetails(_tokenId); } // ======== External: Send Token ========= /** * @notice Send tokens to a recipient on a remote chain * @param _token The token address * @param _amount The token amount * @param _destination The destination domain * @param _recipient The recipient address */ function send( address _token, uint256 _amount, uint32 _destination, bytes32 _recipient ) external { require(_amount > 0, "!amnt"); require(_recipient != bytes32(0), "!recip"); // get remote BridgeRouter address; revert if not found bytes32 _remote = _mustHaveRemote(_destination); // remove tokens from circulation on this chain IERC20 _bridgeToken = IERC20(_token); if (_isLocalOrigin(_bridgeToken)) { // if the token originates on this chain, hold the tokens in escrow // in the Router _bridgeToken.safeTransferFrom(msg.sender, address(this), _amount); } else { // if the token originates on a remote chain, burn the // representation tokens on this chain _downcast(_bridgeToken).burn(msg.sender, _amount); } // format Transfer Tokens action bytes29 _action = BridgeMessage.formatTransfer(_recipient, _amount); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_formatTokenId(_token), _action) ); // emit Send event to record token sender emit Send( address(_bridgeToken), msg.sender, _destination, _recipient, _amount ); } // ======== External: Fast Liquidity ========= /** * @notice Allows a liquidity provider to give an * end user fast liquidity by pre-filling an * incoming transfer message. * Transfers tokens from the liquidity provider to the end recipient, minus the LP fee; * Records the liquidity provider, who receives * the full token amount when the transfer message is handled. * @dev fast liquidity can only be provided for ONE token transfer * with the same (recipient, amount) at a time. * in the case that multiple token transfers with the same (recipient, amount) * @param _message The incoming transfer message to pre-fill */ function preFill(bytes calldata _message) external { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId().mustBeTokenId(); bytes29 _action = _msg.action().mustBeTransfer(); // calculate prefill ID bytes32 _id = _preFillId(_tokenId, _action); // require that transfer has not already been pre-filled require(liquidityProvider[_id] == address(0), "!unfilled"); // record liquidity provider liquidityProvider[_id] = msg.sender; // transfer tokens from liquidity provider to token recipient IERC20 _token = _mustHaveToken(_tokenId); _token.safeTransferFrom( msg.sender, _action.evmRecipient(), _applyPreFillFee(_action.amnt()) ); } // ======== External: Custom Tokens ========= /** * @notice Enroll a custom token. This allows projects to work with * governance to specify a custom representation. * @dev This is done by inserting the custom representation into the token * lookup tables. It is permissioned to the owner (governance) and can * potentially break token representations. It must be used with extreme * caution. * After the token is inserted, new mint instructions will be sent to the * custom token. The default representation (and old custom representations) * may still be burnt. Until all users have explicitly called migrate, both * representations will continue to exist. * The custom representation MUST be trusted, and MUST allow the router to * both mint AND burn tokens at will. * @param _id the canonical ID of the Token to enroll, as a byte vector * @param _custom the address of the custom implementation to use. */ function enrollCustom( uint32 _domain, bytes32 _id, address _custom ) external onlyOwner { // Sanity check. Ensures that human error doesn't cause an // unpermissioned contract to be enrolled. IBridgeToken(_custom).mint(address(this), 1); IBridgeToken(_custom).burn(address(this), 1); // update mappings with custom token bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); representationToCanonical[_custom].domain = _tokenId.domain(); representationToCanonical[_custom].id = _tokenId.id(); bytes32 _idHash = _tokenId.keccak(); canonicalToRepresentation[_idHash] = _custom; } /** * @notice Migrate all tokens in a previous representation to the latest * custom representation. This works by looking up local mappings and then * burning old tokens and minting new tokens. * @dev This is explicitly opt-in to allow dapps to decide when and how to * upgrade to the new representation. * @param _oldRepr The address of the old token to migrate */ function migrate(address _oldRepr) external { // get the token ID for the old token contract TokenId memory _id = representationToCanonical[_oldRepr]; require(_id.domain != 0, "!repr"); // ensure that new token & old token are different IBridgeToken _old = IBridgeToken(_oldRepr); IBridgeToken _new = _representationForCanonical(_id); require(_new != _old, "!different"); // burn the old tokens & mint the new ones uint256 _bal = _old.balanceOf(msg.sender); _old.burn(msg.sender, _bal); _new.mint(msg.sender, _bal); } // ============ Internal: Send / UpdateDetails ============ /** * @notice Given a tokenAddress, format the tokenId * identifier for the message. * @param _token The token address * @param _tokenId The bytes-encoded tokenId */ function _formatTokenId(address _token) internal view returns (bytes29 _tokenId) { TokenId memory _tokId = _tokenIdFor(_token); _tokenId = BridgeMessage.formatTokenId(_tokId.domain, _tokId.id); } // ============ Internal: Handle ============ /** * @notice Handles an incoming Transfer message. * * If the token is of local origin, the amount is sent from escrow. * Otherwise, a representation token is minted. * * @param _tokenId The token ID * @param _action The action */ function _handleTransfer(bytes29 _tokenId, bytes29 _action) internal { // get the token contract for the given tokenId on this chain; // (if the token is of remote origin and there is // no existing representation token contract, the TokenRegistry will // deploy a new one) IERC20 _token = _ensureToken(_tokenId); address _recipient = _action.evmRecipient(); // If an LP has prefilled this token transfer, // send the tokens to the LP instead of the recipient bytes32 _id = _preFillId(_tokenId, _action); address _lp = liquidityProvider[_id]; if (_lp != address(0)) { _recipient = _lp; delete liquidityProvider[_id]; } // send the tokens into circulation on this chain if (_isLocalOrigin(_token)) { // if the token is of local origin, the tokens have been held in // escrow in this contract // while they have been circulating on remote chains; // transfer the tokens to the recipient _token.safeTransfer(_recipient, _action.amnt()); } else { // if the token is of remote origin, mint the tokens to the // recipient on this chain _downcast(_token).mint(_recipient, _action.amnt()); } } /** * @notice Handles an incoming Details message. * @param _tokenId The token ID * @param _action The action */ function _handleDetails(bytes29 _tokenId, bytes29 _action) internal { // get the token contract deployed on this chain // revert if no token contract exists IERC20 _token = _mustHaveToken(_tokenId); // require that the token is of remote origin // (otherwise, the BridgeRouter did not deploy the token contract, // and therefore cannot update its metadata) require(!_isLocalOrigin(_token), "!remote origin"); // update the token metadata _downcast(_token).setDetails( TypeCasts.coerceString(_action.name()), TypeCasts.coerceString(_action.symbol()), _action.decimals() ); } /** * @notice Handles an incoming RequestDetails message by sending an * UpdateDetails message to the remote chain * @dev The origin and remote are pre-checked by the handle function * `onlyRemoteRouter` modifier and can be used without additional check * @param _messageOrigin The domain from which the message arrived * @param _messageRemoteRouter The remote router that sent the message * @param _tokenId The token ID */ function _handleRequestDetails( uint32 _messageOrigin, bytes32 _messageRemoteRouter, bytes29 _tokenId ) internal { // get token & ensure is of local origin address _token = _tokenId.evmId(); require(_isLocalOrigin(_token), "!local origin"); IBridgeToken _bridgeToken = IBridgeToken(_token); // format Update Details message bytes29 _updateDetailsAction = BridgeMessage.formatDetails( TypeCasts.coerceBytes32(_bridgeToken.name()), TypeCasts.coerceBytes32(_bridgeToken.symbol()), _bridgeToken.decimals() ); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _messageOrigin, _messageRemoteRouter, BridgeMessage.formatMessage(_tokenId, _updateDetailsAction) ); } // ============ Internal: Transfer ============ function _ensureToken(bytes29 _tokenId) internal returns (IERC20) { address _local = _getTokenAddress(_tokenId); if (_local == address(0)) { // Representation does not exist yet; // deploy representation contract _local = _deployToken(_tokenId); // message the origin domain // to request the token details _requestDetails(_tokenId); } return IERC20(_local); } // ============ Internal: Request Details ============ /** * @notice Handles an incoming Details message. * @param _tokenId The token ID */ function _requestDetails(bytes29 _tokenId) internal { uint32 _destination = _tokenId.domain(); // get remote BridgeRouter address; revert if not found bytes32 _remote = remotes[_destination]; if (_remote == bytes32(0)) { return; } // format Request Details message bytes29 _action = BridgeMessage.formatRequestDetails(); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_tokenId, _action) ); } // ============ Internal: Fast Liquidity ============ /** * @notice Calculate the token amount after * taking a 5 bps (0.05%) liquidity provider fee * @param _amnt The token amount before the fee is taken * @return _amtAfterFee The token amount after the fee is taken */ function _applyPreFillFee(uint256 _amnt) internal pure returns (uint256 _amtAfterFee) { // overflow only possible if (2**256 / 9995) tokens sent once // in which case, probably not a real token _amtAfterFee = (_amnt * PRE_FILL_FEE_NUMERATOR) / PRE_FILL_FEE_DENOMINATOR; } /** * @notice get the prefillId used to identify * fast liquidity provision for incoming token send messages * @dev used to identify a token/transfer pair in the prefill LP mapping. * NOTE: This approach has a weakness: a user can receive >1 batch of tokens of * the same size, but only 1 will be eligible for fast liquidity. The * other may only be filled at regular speed. This is because the messages * will have identical `tokenId` and `action` fields. This seems fine, * tbqh. A delay of a few hours on a corner case is acceptable in v1. * @param _tokenId The token ID * @param _action The action */ function _preFillId(bytes29 _tokenId, bytes29 _action) internal view returns (bytes32) { bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.joinKeccak(_views); } /** * @dev explicit override for compiler inheritance * @dev explicit override for compiler inheritance * @return domain of chain on which the contract is deployed */ function _localDomain() internal view override(TokenRegistry, XAppConnectionClient) returns (uint32) { return XAppConnectionClient._localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IWeth { function deposit() external payable; function approve(address _who, uint256 _wad) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Home} from "./Home.sol"; import {Replica} from "./Replica.sol"; import {TypeCasts} from "../libs/TypeCasts.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title XAppConnectionManager * @author Celo Labs Inc. * @notice Manages a registry of local Replica contracts * for remote Home domains. Accepts Watcher signatures * to un-enroll Replicas attached to fraudulent remote Homes */ contract XAppConnectionManager is Ownable { // ============ Public Storage ============ // Home contract Home public home; // local Replica address => remote Home domain mapping(address => uint32) public replicaToDomain; // remote Home domain => local Replica address mapping(uint32 => address) public domainToReplica; // watcher address => replica remote domain => has/doesn't have permission mapping(address => mapping(uint32 => bool)) private watcherPermissions; // ============ Events ============ /** * @notice Emitted when a new Replica is enrolled / added * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaEnrolled(uint32 indexed domain, address replica); /** * @notice Emitted when a new Replica is un-enrolled / removed * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaUnenrolled(uint32 indexed domain, address replica); /** * @notice Emitted when Watcher permissions are changed * @param domain the remote domain of the Home contract for the Replica * @param watcher the address of the Watcher * @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed */ event WatcherPermissionSet( uint32 indexed domain, address watcher, bool access ); // ============ Modifiers ============ modifier onlyReplica() { require(isReplica(msg.sender), "!replica"); _; } // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor() Ownable() {} // ============ External Functions ============ /** * @notice Un-Enroll a replica contract * in the case that fraud was detected on the Home * @dev in the future, if fraud occurs on the Home contract, * the Watcher will submit their signature directly to the Home * and it can be relayed to all remote chains to un-enroll the Replicas * @param _domain the remote domain of the Home contract for the Replica * @param _updater the address of the Updater for the Home contract (also stored on Replica) * @param _signature signature of watcher on (domain, replica address, updater address) */ function unenrollReplica( uint32 _domain, bytes32 _updater, bytes memory _signature ) external { // ensure that the replica is currently set address _replica = domainToReplica[_domain]; require(_replica != address(0), "!replica exists"); // ensure that the signature is on the proper updater require( Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater), "!current updater" ); // get the watcher address from the signature // and ensure that the watcher has permission to un-enroll this replica address _watcher = _recoverWatcherFromSig( _domain, TypeCasts.addressToBytes32(_replica), _updater, _signature ); require(watcherPermissions[_watcher][_domain], "!valid watcher"); // remove the replica from mappings _unenrollReplica(_replica); } /** * @notice Set the address of the local Home contract * @param _home the address of the local Home contract */ function setHome(address _home) external onlyOwner { home = Home(_home); } /** * @notice Allow Owner to enroll Replica contract * @param _replica the address of the Replica * @param _domain the remote domain of the Home contract for the Replica */ function ownerEnrollReplica(address _replica, uint32 _domain) external onlyOwner { // un-enroll any existing replica _unenrollReplica(_replica); // add replica and domain to two-way mapping replicaToDomain[_replica] = _domain; domainToReplica[_domain] = _replica; emit ReplicaEnrolled(_domain, _replica); } /** * @notice Allow Owner to un-enroll Replica contract * @param _replica the address of the Replica */ function ownerUnenrollReplica(address _replica) external onlyOwner { _unenrollReplica(_replica); } /** * @notice Allow Owner to set Watcher permissions for a Replica * @param _watcher the address of the Watcher * @param _domain the remote domain of the Home contract for the Replica * @param _access TRUE to give the Watcher permissions, FALSE to remove permissions */ function setWatcherPermission( address _watcher, uint32 _domain, bool _access ) external onlyOwner { watcherPermissions[_watcher][_domain] = _access; emit WatcherPermissionSet(_domain, _watcher, _access); } /** * @notice Query local domain from Home * @return local domain */ function localDomain() external view returns (uint32) { return home.localDomain(); } /** * @notice Get access permissions for the watcher on the domain * @param _watcher the address of the watcher * @param _domain the domain to check for watcher permissions * @return TRUE iff _watcher has permission to un-enroll replicas on _domain */ function watcherPermission(address _watcher, uint32 _domain) external view returns (bool) { return watcherPermissions[_watcher][_domain]; } // ============ Public Functions ============ /** * @notice Check whether _replica is enrolled * @param _replica the replica to check for enrollment * @return TRUE iff _replica is enrolled */ function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; } // ============ Internal Functions ============ /** * @notice Remove the replica from the two-way mappings * @param _replica replica to un-enroll */ function _unenrollReplica(address _replica) internal { uint32 _currentDomain = replicaToDomain[_replica]; domainToReplica[_currentDomain] = address(0); replicaToDomain[_replica] = 0; emit ReplicaUnenrolled(_currentDomain, _replica); } /** * @notice Get the Watcher address from the provided signature * @return address of watcher that signed */ function _recoverWatcherFromSig( uint32 _domain, bytes32 _replica, bytes32 _updater, bytes memory _signature ) internal view returns (address) { bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica)) .homeDomainHash(); bytes32 _digest = keccak256( abi.encodePacked(_homeDomainHash, _domain, _updater) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return ECDSA.recover(_digest, _signature); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeMessage} from "./BridgeMessage.sol"; import {Encoding} from "./Encoding.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {UpgradeBeaconProxy} from "@celo-org/optics-sol/contracts/upgrade/UpgradeBeaconProxy.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title TokenRegistry * @notice manages a registry of token contracts on this chain * - * We sort token types as "representation token" or "locally originating token". * Locally originating - a token contract that was originally deployed on the local chain * Representation (repr) - a token that was originally deployed on some other chain * - * When the router handles an incoming message, it determines whether the * transfer is for an asset of local origin. If not, it checks for an existing * representation contract. If no such representation exists, it deploys a new * representation contract. It then stores the relationship in the * "reprToCanonical" and "canonicalToRepr" mappings to ensure we can always * perform a lookup in either direction * Note that locally originating tokens should NEVER be represented in these lookup tables. */ abstract contract TokenRegistry is Initializable { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; // ============ Structs ============ // Tokens are identified by a TokenId: // domain - 4 byte chain ID of the chain from which the token originates // id - 32 byte identifier of the token address on the origin chain, in that chain's address format struct TokenId { uint32 domain; bytes32 id; } // ============ Public Storage ============ // UpgradeBeacon from which new token proxies will get their implementation address public tokenBeacon; // local representation token address => token ID mapping(address => TokenId) public representationToCanonical; // hash of the tightly-packed TokenId => local representation token address // If the token is of local origin, this MUST map to address(0). mapping(bytes32 => address) public canonicalToRepresentation; // ============ Events ============ event TokenDeployed( uint32 indexed domain, bytes32 indexed id, address indexed representation ); // ======== Initializer ========= /** * @notice Initialize the TokenRegistry with UpgradeBeaconController and * XappConnectionManager. * @dev This method deploys two new contracts, and may be expensive to call. * @param _tokenBeacon The address of the upgrade beacon for bridge token * proxies */ function __TokenRegistry_initialize(address _tokenBeacon) internal initializer { tokenBeacon = _tokenBeacon; } // ======== External: Token Lookup Convenience ========= /** * @notice Looks up the canonical identifier for a local representation. * @dev If no such canonical ID is known, this instead returns (0, bytes32(0)) * @param _local The local address of the representation */ function getCanonicalAddress(address _local) external view returns (uint32 _domain, bytes32 _id) { TokenId memory _canonical = representationToCanonical[_local]; _domain = _canonical.domain; _id = _canonical.id; } /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, address _id) external view returns (address _token) { _token = getLocalAddress(_domain, TypeCasts.addressToBytes32(_id)); } // ======== Public: Token Lookup Convenience ========= /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, bytes32 _id) public view returns (address _token) { _token = _getTokenAddress(BridgeMessage.formatTokenId(_domain, _id)); } // ======== Internal Functions ========= function _localDomain() internal view virtual returns (uint32); /** * @notice Get default name and details for a token * Sets name to "optics.[domain].[id]" * and symbol to * @param _tokenId the tokenId for the token */ function _defaultDetails(bytes29 _tokenId) internal pure returns (string memory _name, string memory _symbol) { // get the first and second half of the token ID (, uint256 _secondHalfId) = Encoding.encodeHex(uint256(_tokenId.id())); // encode the default token name: "[decimal domain].[hex 4 bytes of ID]" _name = string( abi.encodePacked( Encoding.decimalUint32(_tokenId.domain()), // 10 ".", // 1 uint32(_secondHalfId) // 4 ) ); // allocate the memory for a new 32-byte string _symbol = new string(10 + 1 + 4); assembly { mstore(add(_symbol, 0x20), mload(add(_name, 0x20))) } } /** * @notice Deploy and initialize a new token contract * @dev Each token contract is a proxy which * points to the token upgrade beacon * @return _token the address of the token contract */ function _deployToken(bytes29 _tokenId) internal returns (address _token) { // deploy and initialize the token contract _token = address(new UpgradeBeaconProxy(tokenBeacon, "")); // initialize the token separately from the IBridgeToken(_token).initialize(); // set the default token name & symbol string memory _name; string memory _symbol; (_name, _symbol) = _defaultDetails(_tokenId); IBridgeToken(_token).setDetails(_name, _symbol, 18); // store token in mappings representationToCanonical[_token].domain = _tokenId.domain(); representationToCanonical[_token].id = _tokenId.id(); canonicalToRepresentation[_tokenId.keccak()] = _token; // emit event upon deploying new token emit TokenDeployed(_tokenId.domain(), _tokenId.id(), _token); } /** * @notice Get the local token address * for the canonical token represented by tokenID * Returns address(0) if canonical token is of remote origin * and no representation token has been deployed locally * @param _tokenId the token id of the canonical token * @return _local the local token address */ function _getTokenAddress(bytes29 _tokenId) internal view returns (address _local) { if (_tokenId.domain() == _localDomain()) { // Token is of local origin _local = _tokenId.evmId(); } else { // Token is a representation of a token of remote origin _local = canonicalToRepresentation[_tokenId.keccak()]; } } /** * @notice Return the local token contract for the * canonical tokenId; revert if there is no local token * @param _tokenId the token id of the canonical token * @return the IERC20 token contract */ function _mustHaveToken(bytes29 _tokenId) internal view returns (IERC20) { address _local = _getTokenAddress(_tokenId); require(_local != address(0), "!token"); return IERC20(_local); } /** * @notice Return tokenId for a local token address * @param _token local token address (representation or canonical) * @return _id local token address (representation or canonical) */ function _tokenIdFor(address _token) internal view returns (TokenId memory _id) { _id = representationToCanonical[_token]; if (_id.domain == 0) { _id.domain = _localDomain(); _id.id = TypeCasts.addressToBytes32(_token); } } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(IERC20 _token) internal view returns (bool) { return _isLocalOrigin(address(_token)); } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(address _token) internal view returns (bool) { // If the contract WAS deployed by the TokenRegistry, // it will be stored in this mapping. // If so, it IS NOT of local origin if (representationToCanonical[_token].domain != 0) { return false; } // If the contract WAS NOT deployed by the TokenRegistry, // and the contract exists, then it IS of local origin // Return true if code exists at _addr uint256 _codeSize; // solhint-disable-next-line no-inline-assembly assembly { _codeSize := extcodesize(_token) } return _codeSize != 0; } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(bytes29 _tokenId) internal view returns (IBridgeToken) { return IBridgeToken(canonicalToRepresentation[_tokenId.keccak()]); } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(TokenId memory _tokenId) internal view returns (IBridgeToken) { return _representationForCanonical(_serializeId(_tokenId)); } /** * @notice downcast an IERC20 to an IBridgeToken * @dev Unsafe. Please know what you're doing * @param _token the IERC20 contract * @return the IBridgeToken contract */ function _downcast(IERC20 _token) internal pure returns (IBridgeToken) { return IBridgeToken(address(_token)); } /** * @notice serialize a TokenId struct into a bytes view * @param _id the tokenId * @return serialized bytes of tokenId */ function _serializeId(TokenId memory _id) internal pure returns (bytes29) { return BridgeMessage.formatTokenId(_id.domain, _id.id); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {XAppConnectionClient} from "./XAppConnectionClient.sol"; // ============ External Imports ============ import {IMessageRecipient} from "@celo-org/optics-sol/interfaces/IMessageRecipient.sol"; abstract contract Router is XAppConnectionClient, IMessageRecipient { // ============ Mutable Storage ============ mapping(uint32 => bytes32) public remotes; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from a remote Router contract * @param _origin The domain the message is coming from * @param _router The address the message is coming from */ modifier onlyRemoteRouter(uint32 _origin, bytes32 _router) { require(_isRemoteRouter(_origin, _router), "!remote router"); _; } // ============ External functions ============ /** * @notice Register the address of a Router contract for the same xApp on a remote chain * @param _domain The domain of the remote xApp Router * @param _router The address of the remote xApp Router */ function enrollRemoteRouter(uint32 _domain, bytes32 _router) external onlyOwner { remotes[_domain] = _router; } // ============ Virtual functions ============ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external virtual override; // ============ Internal functions ============ /** * @notice Return true if the given domain / router is the address of a remote xApp Router * @param _domain The domain of the potential remote xApp Router * @param _router The address of the potential remote xApp Router */ function _isRemoteRouter(uint32 _domain, bytes32 _router) internal view returns (bool) { return remotes[_domain] == _router; } /** * @notice Assert that the given domain has a xApp Router registered and return its address * @param _domain The domain of the chain for which to get the xApp Router * @return _remote The address of the remote xApp Router on _domain */ function _mustHaveRemote(uint32 _domain) internal view returns (bytes32 _remote) { _remote = remotes[_domain]; require(_remote != bytes32(0), "!remote"); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {XAppConnectionManager} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; abstract contract XAppConnectionClient is OwnableUpgradeable { // ============ Mutable Storage ============ XAppConnectionManager public xAppConnectionManager; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from an Optics Replica contract */ modifier onlyReplica() { require(_isReplica(msg.sender), "!replica"); _; } // ======== Initializer ========= function __XAppConnectionClient_initialize(address _xAppConnectionManager) internal initializer { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); __Ownable_init(); } // ============ External functions ============ /** * @notice Modify the contract the xApp uses to validate Replica contracts * @param _xAppConnectionManager The address of the xAppConnectionManager contract */ function setXAppConnectionManager(address _xAppConnectionManager) external onlyOwner { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); } // ============ Internal functions ============ /** * @notice Get the local Home contract from the xAppConnectionManager * @return The local Home contract */ function _home() internal view returns (Home) { return xAppConnectionManager.home(); } /** * @notice Determine whether _potentialReplcia is an enrolled Replica from the xAppConnectionManager * @return True if _potentialReplica is an enrolled Replica */ function _isReplica(address _potentialReplica) internal view returns (bool) { return xAppConnectionManager.isReplica(_potentialReplica); } /** * @notice Get the local domain from the xAppConnectionManager * @return The local domain */ function _localDomain() internal view virtual returns (uint32) { return xAppConnectionManager.localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IBridgeToken { function initialize() external; function name() external returns (string memory); function balanceOf(address _account) external view returns (uint256); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function burn(address _from, uint256 _amnt) external; function mint(address _to, uint256 _amnt) external; function setDetails( string calldata _name, string calldata _symbol, uint8 _decimals ) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library BridgeMessage { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; // ============ Enums ============ // WARNING: do NOT re-write the numbers / order // of message types in an upgrade; // will cause in-flight messages to be mis-interpreted enum Types { Invalid, // 0 TokenId, // 1 Message, // 2 Transfer, // 3 Details, // 4 RequestDetails // 5 } // ============ Constants ============ uint256 private constant TOKEN_ID_LEN = 36; // 4 bytes domain + 32 bytes id uint256 private constant IDENTIFIER_LEN = 1; uint256 private constant TRANSFER_LEN = 65; // 1 byte identifier + 32 bytes recipient + 32 bytes amount uint256 private constant DETAILS_LEN = 66; // 1 byte identifier + 32 bytes name + 32 bytes symbol + 1 byte decimals uint256 private constant REQUEST_DETAILS_LEN = 1; // 1 byte identifier // ============ Modifiers ============ /** * @notice Asserts a message is of type `_t` * @param _view The message * @param _t The expected type */ modifier typeAssert(bytes29 _view, Types _t) { _view.assertType(uint40(_t)); _; } // ============ Internal Functions ============ /** * @notice Checks that Action is valid type * @param _action The action * @return TRUE if action is valid */ function isValidAction(bytes29 _action) internal pure returns (bool) { return isDetails(_action) || isRequestDetails(_action) || isTransfer(_action); } /** * @notice Checks that view is a valid message length * @param _view The bytes string * @return TRUE if message is valid */ function isValidMessageLength(bytes29 _view) internal pure returns (bool) { uint256 _len = _view.len(); return _len == TOKEN_ID_LEN + TRANSFER_LEN || _len == TOKEN_ID_LEN + DETAILS_LEN || _len == TOKEN_ID_LEN + REQUEST_DETAILS_LEN; } /** * @notice Formats an action message * @param _tokenId The token ID * @param _action The action * @return The formatted message */ function formatMessage(bytes29 _tokenId, bytes29 _action) internal view typeAssert(_tokenId, Types.TokenId) returns (bytes memory) { require(isValidAction(_action), "!action"); bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.join(_views); } /** * @notice Returns the type of the message * @param _view The message * @return The type of the message */ function messageType(bytes29 _view) internal pure returns (Types) { return Types(uint8(_view.typeOf())); } /** * @notice Checks that the message is of type Transfer * @param _action The message * @return True if the message is of type Transfer */ function isTransfer(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Transfer) && messageType(_action) == Types.Transfer; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Details) && messageType(_action) == Types.Details; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isRequestDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.RequestDetails) && messageType(_action) == Types.RequestDetails; } /** * @notice Formats Transfer * @param _to The recipient address as bytes32 * @param _amnt The transfer amount * @return */ function formatTransfer(bytes32 _to, uint256 _amnt) internal pure returns (bytes29) { return mustBeTransfer(abi.encodePacked(Types.Transfer, _to, _amnt).ref(0)); } /** * @notice Formats Details * @param _name The name * @param _symbol The symbol * @param _decimals The decimals * @return The Details message */ function formatDetails( bytes32 _name, bytes32 _symbol, uint8 _decimals ) internal pure returns (bytes29) { return mustBeDetails( abi.encodePacked(Types.Details, _name, _symbol, _decimals).ref( 0 ) ); } /** * @notice Formats Request Details * @return The Request Details message */ function formatRequestDetails() internal pure returns (bytes29) { return mustBeRequestDetails(abi.encodePacked(Types.RequestDetails).ref(0)); } /** * @notice Formats the Token ID * @param _domain The domain * @param _id The ID * @return The formatted Token ID */ function formatTokenId(uint32 _domain, bytes32 _id) internal pure returns (bytes29) { return mustBeTokenId(abi.encodePacked(_domain, _id).ref(0)); } /** * @notice Retrieves the domain from a TokenID * @param _tokenId The message * @return The domain */ function domain(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (uint32) { return uint32(_tokenId.indexUint(0, 4)); } /** * @notice Retrieves the ID from a TokenID * @param _tokenId The message * @return The ID */ function id(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (bytes32) { // before = 4 bytes domain return _tokenId.index(4, 32); } /** * @notice Retrieves the EVM ID * @param _tokenId The message * @return The EVM ID */ function evmId(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (address) { // before = 4 bytes domain + 12 bytes empty to trim for address return _tokenId.indexAddress(16); } /** * @notice Retrieves the action identifier from message * @param _message The action * @return The message type */ function msgType(bytes29 _message) internal pure returns (uint8) { return uint8(_message.indexUint(TOKEN_ID_LEN, 1)); } /** * @notice Retrieves the identifier from action * @param _action The action * @return The action type */ function actionType(bytes29 _action) internal pure returns (uint8) { return uint8(_action.indexUint(0, 1)); } /** * @notice Retrieves the recipient from a Transfer * @param _transferAction The message * @return The recipient address as bytes32 */ function recipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (bytes32) { // before = 1 byte identifier return _transferAction.index(1, 32); } /** * @notice Retrieves the EVM Recipient from a Transfer * @param _transferAction The message * @return The EVM Recipient */ function evmRecipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (address) { // before = 1 byte identifier + 12 bytes empty to trim for address return _transferAction.indexAddress(13); } /** * @notice Retrieves the amount from a Transfer * @param _transferAction The message * @return The amount */ function amnt(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (uint256) { // before = 1 byte identifier + 32 bytes ID return _transferAction.indexUint(33, 32); } /** * @notice Retrieves the name from Details * @param _detailsAction The message * @return The name */ function name(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier return _detailsAction.index(1, 32); } /** * @notice Retrieves the symbol from Details * @param _detailsAction The message * @return The symbol */ function symbol(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier + 32 bytes name return _detailsAction.index(33, 32); } /** * @notice Retrieves the decimals from Details * @param _detailsAction The message * @return The decimals */ function decimals(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (uint8) { // before = 1 byte identifier + 32 bytes name + 32 bytes symbol return uint8(_detailsAction.indexUint(65, 1)); } /** * @notice Retrieves the token ID from a Message * @param _message The message * @return The ID */ function tokenId(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { return _message.slice(0, TOKEN_ID_LEN, uint40(Types.TokenId)); } /** * @notice Retrieves the action data from a Message * @param _message The message * @return The action */ function action(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { uint256 _actionLen = _message.len() - TOKEN_ID_LEN; uint40 _type = uint40(msgType(_message)); return _message.slice(TOKEN_ID_LEN, _actionLen, _type); } /** * @notice Converts to a Transfer * @param _action The message * @return The newly typed message */ function tryAsTransfer(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == TRANSFER_LEN) { return _action.castTo(uint40(Types.Transfer)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == DETAILS_LEN) { return _action.castTo(uint40(Types.Details)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsRequestDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == REQUEST_DETAILS_LEN) { return _action.castTo(uint40(Types.RequestDetails)); } return TypedMemView.nullView(); } /** * @notice Converts to a TokenID * @param _tokenId The message * @return The newly typed message */ function tryAsTokenId(bytes29 _tokenId) internal pure returns (bytes29) { if (_tokenId.len() == TOKEN_ID_LEN) { return _tokenId.castTo(uint40(Types.TokenId)); } return TypedMemView.nullView(); } /** * @notice Converts to a Message * @param _message The message * @return The newly typed message */ function tryAsMessage(bytes29 _message) internal pure returns (bytes29) { if (isValidMessageLength(_message)) { return _message.castTo(uint40(Types.Message)); } return TypedMemView.nullView(); } /** * @notice Asserts that the message is of type Transfer * @param _view The message * @return The message */ function mustBeTransfer(bytes29 _view) internal pure returns (bytes29) { return tryAsTransfer(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeRequestDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsRequestDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type TokenID * @param _view The message * @return The message */ function mustBeTokenId(bytes29 _view) internal pure returns (bytes29) { return tryAsTokenId(_view).assertValid(); } /** * @notice Asserts that the message is of type Message * @param _view The message * @return The message */ function mustBeMessage(bytes29 _view) internal pure returns (bytes29) { return tryAsMessage(_view).assertValid(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {QueueLib} from "../libs/Queue.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {MerkleTreeManager} from "./Merkle.sol"; import {QueueManager} from "./Queue.sol"; import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol"; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Home * @author Celo Labs Inc. * @notice Accepts messages to be dispatched to remote chains, * constructs a Merkle tree of the messages, * and accepts signatures from a bonded Updater * which notarize the Merkle tree roots. * Accepts submissions of fraudulent signatures * by the Updater and slashes the Updater in this case. */ contract Home is Version0, QueueManager, MerkleTreeManager, Common, OwnableUpgradeable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; using MerkleLib for MerkleLib.Tree; // ============ Constants ============ // Maximum bytes per message = 2 KiB // (somewhat arbitrarily set to begin) uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10; // ============ Public Storage Variables ============ // domain => next available nonce for the domain mapping(uint32 => uint32) public nonces; // contract responsible for Updater bonding, slashing and rotation IUpdaterManager public updaterManager; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[48] private __GAP; // ============ Events ============ /** * @notice Emitted when a new message is dispatched via Optics * @param leafIndex Index of message's leaf in merkle tree * @param destinationAndNonce Destination and destination-specific * nonce combined in single field ((destination << 32) & nonce) * @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message * @param committedRoot the latest notarized root submitted in the last signed Update * @param message Raw bytes of message */ event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message ); /** * @notice Emitted when proof of an improper update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root of the improper update * @param newRoot New root of the improper update * @param signature Signature on `oldRoot` and `newRoot */ event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature); /** * @notice Emitted when the Updater is slashed * (should be paired with ImproperUpdater or DoubleUpdate event) * @param updater The address of the updater * @param reporter The address of the entity that reported the updater misbehavior */ event UpdaterSlashed(address indexed updater, address indexed reporter); /** * @notice Emitted when Updater is rotated by the UpdaterManager * @param updater The address of the new updater */ event NewUpdater(address updater); /** * @notice Emitted when the UpdaterManager contract is changed * @param updaterManager The address of the new updaterManager */ event NewUpdaterManager(address updaterManager); // ============ Constructor ============ constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks // ============ Initializer ============ function initialize(IUpdaterManager _updaterManager) public initializer { // initialize owner & queue __Ownable_init(); __QueueManager_initialize(); // set Updater Manager contract and initialize Updater _setUpdaterManager(_updaterManager); address _updater = updaterManager.updater(); __Common_initialize(_updater); emit NewUpdater(_updater); } // ============ Modifiers ============ /** * @notice Ensures that function is called by the UpdaterManager contract */ modifier onlyUpdaterManager() { require(msg.sender == address(updaterManager), "!updaterManager"); _; } // ============ External: Updater & UpdaterManager Configuration ============ /** * @notice Set a new Updater * @param _updater the new Updater */ function setUpdater(address _updater) external onlyUpdaterManager { _setUpdater(_updater); } /** * @notice Set a new UpdaterManager contract * @dev Home(s) will initially be initialized using a trusted UpdaterManager contract; * we will progressively decentralize by swapping the trusted contract with a new implementation * that implements Updater bonding & slashing, and rules for Updater selection & rotation * @param _updaterManager the new UpdaterManager contract */ function setUpdaterManager(address _updaterManager) external onlyOwner { _setUpdaterManager(IUpdaterManager(_updaterManager)); } // ============ External Functions ============ /** * @notice Dispatch the message it to the destination domain & recipient * @dev Format the message, insert its hash into Merkle tree, * enqueue the new Merkle root, and emit `Dispatch` event with message information. * @param _destinationDomain Domain of destination chain * @param _recipientAddress Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes content of message */ function dispatch( uint32 _destinationDomain, bytes32 _recipientAddress, bytes memory _messageBody ) external notFailed { require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long"); // get the next nonce for the destination domain, then increment it uint32 _nonce = nonces[_destinationDomain]; nonces[_destinationDomain] = _nonce + 1; // format the message into packed bytes bytes memory _message = Message.formatMessage( localDomain, bytes32(uint256(uint160(msg.sender))), _nonce, _destinationDomain, _recipientAddress, _messageBody ); // insert the hashed message into the Merkle tree bytes32 _messageHash = keccak256(_message); tree.insert(_messageHash); // enqueue the new Merkle root after inserting the message queue.enqueue(root()); // Emit Dispatch event with message information // note: leafIndex is count() - 1 since new leaf has already been inserted emit Dispatch( _messageHash, count() - 1, _destinationAndNonce(_destinationDomain, _nonce), committedRoot, _message ); } /** * @notice Submit a signature from the Updater "notarizing" a root, * which updates the Home contract's `committedRoot`, * and publishes the signature which will be relayed to Replica contracts * @dev emits Update event * @dev If _newRoot is not contained in the queue, * the Update is a fraudulent Improper Update, so * the Updater is slashed & Home is set to FAILED state * @param _committedRoot Current updated merkle root which the update is building off of * @param _newRoot New merkle root to update the contract state to * @param _signature Updater signature on `_committedRoot` and `_newRoot` */ function update( bytes32 _committedRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // check that the update is not fraudulent; // if fraud is detected, Updater is slashed & Home is set to FAILED state if (improperUpdate(_committedRoot, _newRoot, _signature)) return; // clear all of the intermediate roots contained in this update from the queue while (true) { bytes32 _next = queue.dequeue(); if (_next == _newRoot) break; } // update the Home state with the latest signed root & emit event committedRoot = _newRoot; emit Update(localDomain, _committedRoot, _newRoot, _signature); } /** * @notice Suggest an update for the Updater to sign and submit. * @dev If queue is empty, null bytes returned for both * (No update is necessary because no messages have been dispatched since the last update) * @return _committedRoot Latest root signed by the Updater * @return _new Latest enqueued Merkle root */ function suggestUpdate() external view returns (bytes32 _committedRoot, bytes32 _new) { if (queue.length() != 0) { _committedRoot = committedRoot; _new = queue.lastItem(); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(localDomain); } /** * @notice Check if an Update is an Improper Update; * if so, slash the Updater and set the contract to FAILED state. * * An Improper Update is an update building off of the Home's `committedRoot` * for which the `_newRoot` does not currently exist in the Home's queue. * This would mean that message(s) that were not truly * dispatched on Home were falsely included in the signed root. * * An Improper Update will only be accepted as valid by the Replica * If an Improper Update is attempted on Home, * the Updater will be slashed immediately. * If an Improper Update is submitted to the Replica, * it should be relayed to the Home contract using this function * in order to slash the Updater with an Improper Update. * * An Improper Update submitted to the Replica is only valid * while the `_oldRoot` is still equal to the `committedRoot` on Home; * if the `committedRoot` on Home has already been updated with a valid Update, * then the Updater should be slashed with a Double Update. * @dev Reverts (and doesn't slash updater) if signature is invalid or * update not current * @param _oldRoot Old merkle tree root (should equal home's committedRoot) * @param _newRoot New merkle tree root * @param _signature Updater signature on `_oldRoot` and `_newRoot` * @return TRUE if update was an Improper Update (implying Updater was slashed) */ function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) public notFailed returns (bool) { require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); require(_oldRoot == committedRoot, "not a current update"); // if the _newRoot is not currently contained in the queue, // slash the Updater and set the contract to FAILED state if (!queue.contains(_newRoot)) { _fail(); emit ImproperUpdate(_oldRoot, _newRoot, _signature); return true; } // if the _newRoot is contained in the queue, // this is not an improper update return false; } // ============ Internal Functions ============ /** * @notice Set the UpdaterManager * @param _updaterManager Address of the UpdaterManager */ function _setUpdaterManager(IUpdaterManager _updaterManager) internal { require( Address.isContract(address(_updaterManager)), "!contract updaterManager" ); updaterManager = IUpdaterManager(_updaterManager); emit NewUpdaterManager(address(_updaterManager)); } /** * @notice Set the Updater * @param _updater Address of the Updater */ function _setUpdater(address _updater) internal { updater = _updater; emit NewUpdater(_updater); } /** * @notice Slash the Updater and set contract state to FAILED * @dev Called when fraud is proven (Improper Update or Double Update) */ function _fail() internal override { // set contract to FAILED _setFailed(); // slash Updater updaterManager.slashUpdater(msg.sender); emit UpdaterSlashed(updater, msg.sender); } /** * @notice Internal utility function that combines * `_destination` and `_nonce`. * @dev Both destination and nonce should be less than 2^32 - 1 * @param _destination Domain of destination chain * @param _nonce Current nonce for given destination chain * @return Returns (`_destination` << 32) & `_nonce` */ function _destinationAndNonce(uint32 _destination, uint32 _nonce) internal pure returns (uint64) { return (uint64(_destination) << 32) | _nonce; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title Version0 * @notice Version getter for contracts **/ contract Version0 { uint8 public constant VERSION = 0; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.5.10; import {SafeMath} from "./SafeMath.sol"; library TypedMemView { using SafeMath for uint256; // Why does this exist? // the solidity `bytes memory` type has a few weaknesses. // 1. You can't index ranges effectively // 2. You can't slice without copying // 3. The underlying data may represent any type // 4. Solidity never deallocates memory, and memory costs grow // superlinearly // By using a memory view instead of a `bytes memory` we get the following // advantages: // 1. Slices are done on the stack, by manipulating the pointer // 2. We can index arbitrary ranges and quickly convert them to stack types // 3. We can insert type info into the pointer, and typecheck at runtime // This makes `TypedMemView` a useful tool for efficient zero-copy // algorithms. // Why bytes29? // We want to avoid confusion between views, digests, and other common // types so we chose a large and uncommonly used odd number of bytes // // Note that while bytes are left-aligned in a word, integers and addresses // are right-aligned. This means when working in assembly we have to // account for the 3 unused bytes on the righthand side // // First 5 bytes are a type flag. // - ff_ffff_fffe is reserved for unknown type. // - ff_ffff_ffff is reserved for invalid types/errors. // next 12 are memory address // next 12 are len // bottom 3 bytes are empty // Assumptions: // - non-modification of memory. // - No Solidity updates // - - wrt free mem point // - - wrt bytes representation in memory // - - wrt memory addressing in general // Usage: // - create type constants // - use `assertType` for runtime type assertions // - - unfortunately we can't do this at compile time yet :( // - recommended: implement modifiers that perform type checking // - - e.g. // - - `uint40 constant MY_TYPE = 3;` // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }` // - instantiate a typed view from a bytearray using `ref` // - use `index` to inspect the contents of the view // - use `slice` to create smaller views into the same memory // - - `slice` can increase the offset // - - `slice can decrease the length` // - - must specify the output type of `slice` // - - `slice` will return a null view if you try to overrun // - - make sure to explicitly check for this with `notNull` or `assertType` // - use `equal` for typed comparisons. // The null view bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff; uint8 constant TWELVE_BYTES = 96; /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _b The byte * @return char - The encoded hex character */ function nibbleHex(uint8 _b) internal pure returns (uint8 char) { // This can probably be done more efficiently, but it's only in error // paths, so we don't really care :) uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4 if (_nibble == 0xf0) {return 0x30;} // 0 if (_nibble == 0xf1) {return 0x31;} // 1 if (_nibble == 0xf2) {return 0x32;} // 2 if (_nibble == 0xf3) {return 0x33;} // 3 if (_nibble == 0xf4) {return 0x34;} // 4 if (_nibble == 0xf5) {return 0x35;} // 5 if (_nibble == 0xf6) {return 0x36;} // 6 if (_nibble == 0xf7) {return 0x37;} // 7 if (_nibble == 0xf8) {return 0x38;} // 8 if (_nibble == 0xf9) {return 0x39;} // 9 if (_nibble == 0xfa) {return 0x61;} // a if (_nibble == 0xfb) {return 0x62;} // b if (_nibble == 0xfc) {return 0x63;} // c if (_nibble == 0xfd) {return 0x64;} // d if (_nibble == 0xfe) {return 0x65;} // e if (_nibble == 0xff) {return 0x66;} // f } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _b The byte * @return encoded - The hex-encoded byte */ function byteHex(uint8 _b) internal pure returns (uint16 encoded) { encoded |= nibbleHex(_b >> 4); // top 4 bits encoded <<= 8; encoded |= nibbleHex(_b); // lower 4 bits } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * * @param _b The 32 bytes as uint256 * @return first - The top 16 bytes * @return second - The bottom 16 bytes */ function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); first |= byteHex(_byte); if (i != 16) { first <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255 ; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); second |= byteHex(_byte); if (i != 0) { second <<= 16; } } } /** * @notice Changes the endianness of a uint256. * @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel * @param _b The unsigned integer to reverse * @return v - The reversed value */ function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /** * @notice Create a mask with the highest `_len` bits set. * @param _len The length * @return mask - The mask */ function leftMask(uint8 _len) private pure returns (uint256 mask) { // ugly. redo without assembly? assembly { // solium-disable-previous-line security/no-inline-assembly mask := sar( sub(_len, 1), 0x8000000000000000000000000000000000000000000000000000000000000000 ) } } /** * @notice Return the null view. * @return bytes29 - The null view */ function nullView() internal pure returns (bytes29) { return NULL; } /** * @notice Check if the view is null. * @return bool - True if the view is null */ function isNull(bytes29 memView) internal pure returns (bool) { return memView == NULL; } /** * @notice Check if the view is not null. * @return bool - True if the view is not null */ function notNull(bytes29 memView) internal pure returns (bool) { return !isNull(memView); } /** * @notice Check if the view is of a valid type and points to a valid location * in memory. * @dev We perform this check by examining solidity's unallocated memory * pointer and ensuring that the view's upper bound is less than that. * @param memView The view * @return ret - True if the view is valid */ function isValid(bytes29 memView) internal pure returns (bool ret) { if (typeOf(memView) == 0xffffffffff) {return false;} uint256 _end = end(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ret := not(gt(_end, mload(0x40))) } } /** * @notice Require that a typed memory view be valid. * @dev Returns the view for easy chaining. * @param memView The view * @return bytes29 - The validated view */ function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; } /** * @notice Return true if the memview is of the expected type. Otherwise false. * @param memView The view * @param _expected The expected type * @return bool - True if the memview is of the expected type */ function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) { return typeOf(memView) == _expected; } /** * @notice Require that a typed memory view has a specific type. * @dev Returns the view for easy chaining. * @param memView The view * @param _expected The expected type * @return bytes29 - The view with validated type */ function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) { if (!isType(memView, _expected)) { (, uint256 g) = encodeHex(uint256(typeOf(memView))); (, uint256 e) = encodeHex(uint256(_expected)); string memory err = string( abi.encodePacked( "Type assertion failed. Got 0x", uint80(g), ". Expected 0x", uint80(e) ) ); revert(err); } return memView; } /** * @notice Return an identical view with a different type. * @param memView The view * @param _newType The new type * @return newView - The new view with the specified type */ function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } } /** * @notice Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) { assembly { // solium-disable-previous-line security/no-inline-assembly newView := shl(96, or(newView, _type)) // insert type newView := shl(96, or(newView, _loc)) // insert loc newView := shl(24, or(newView, _len)) // empty bottom 3 bytes } } /** * @notice Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) { uint256 _end = _loc.add(_len); assembly { // solium-disable-previous-line security/no-inline-assembly if gt(_end, mload(0x40)) { _end := 0 } } if (_end == 0) { return NULL; } newView = unsafeBuildUnchecked(_type, _loc, _len); } /** * @notice Instantiate a memory view from a byte array. * @dev Note that due to Solidity memory representation, it is not possible to * implement a deref, as the `bytes` type stores its len in memory. * @param arr The byte array * @param newType The type * @return bytes29 - The memory view */ function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) { uint256 _len = arr.length; uint256 _loc; assembly { // solium-disable-previous-line security/no-inline-assembly _loc := add(arr, 0x20) // our view is of the data, not the struct } return build(newType, _loc, _len); } /** * @notice Return the associated type information. * @param memView The memory view * @return _type - The type associated with the view */ function typeOf(bytes29 memView) internal pure returns (uint40 _type) { assembly { // solium-disable-previous-line security/no-inline-assembly // 216 == 256 - 40 _type := shr(216, memView) // shift out lower 24 bytes } } /** * @notice Optimized type comparison. Checks that the 5-byte type flag is equal. * @param left The first view * @param right The second view * @return bool - True if the 5-byte type flag is equal */ function sameType(bytes29 left, bytes29 right) internal pure returns (bool) { return (left ^ right) >> (2 * TWELVE_BYTES) == 0; } /** * @notice Return the memory address of the underlying bytes. * @param memView The view * @return _loc - The memory address */ function loc(bytes29 memView) internal pure returns (uint96 _loc) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly // 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space) _loc := and(shr(120, memView), _mask) } } /** * @notice The number of memory words this memory view occupies, rounded up. * @param memView The view * @return uint256 - The number of memory words */ function words(bytes29 memView) internal pure returns (uint256) { return uint256(len(memView)).add(32) / 32; } /** * @notice The in-memory footprint of a fresh copy of the view. * @param memView The view * @return uint256 - The in-memory footprint of a fresh copy of the view. */ function footprint(bytes29 memView) internal pure returns (uint256) { return words(memView) * 32; } /** * @notice The number of bytes of the view. * @param memView The view * @return _len - The length of the view */ function len(bytes29 memView) internal pure returns (uint96 _len) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly _len := and(shr(24, memView), _mask) } } /** * @notice Returns the endpoint of `memView`. * @param memView The view * @return uint256 - The endpoint of `memView` */ function end(bytes29 memView) internal pure returns (uint256) { return loc(memView) + len(memView); } /** * @notice Safe slicing without memory modification. * @param memView The view * @param _index The start index * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) { uint256 _loc = loc(memView); // Ensure it doesn't overrun the view if (_loc.add(_index).add(_len) > end(memView)) { return NULL; } _loc = _loc.add(_index); return build(newType, _loc, _len); } /** * @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, 0, _len, newType); } /** * @notice Shortcut to `slice`. Gets a view representing the last `_len` byte. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, uint256(len(memView)).sub(_len), _len, newType); } /** * @notice Construct an error message for an indexing overrun. * @param _loc The memory address * @param _len The length * @param _index The index * @param _slice The slice where the overrun occurred * @return err - The err */ function indexErrOverrun( uint256 _loc, uint256 _len, uint256 _index, uint256 _slice ) internal pure returns (string memory err) { (, uint256 a) = encodeHex(_loc); (, uint256 b) = encodeHex(_len); (, uint256 c) = encodeHex(_index); (, uint256 d) = encodeHex(_slice); err = string( abi.encodePacked( "TypedMemView/index - Overran the view. Slice is at 0x", uint48(a), " with length 0x", uint48(b), ". Attempted to index at offset 0x", uint48(c), " with length 0x", uint48(d), "." ) ); } /** * @notice Load up to 32 bytes from the view onto the stack. * @dev Returns a bytes32 with only the `_bytes` highest bytes set. * This can be immediately cast to a smaller fixed-length byte array. * To automatically cast to an integer, use `indexUint`. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The 32 byte result */ function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) { if (_bytes == 0) {return bytes32(0);} if (_index.add(_bytes) > len(memView)) { revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes))); } require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes"); uint8 bitLength = _bytes * 8; uint256 _loc = loc(memView); uint256 _mask = leftMask(bitLength); assembly { // solium-disable-previous-line security/no-inline-assembly result := and(mload(add(_loc, _index)), _mask) } } /** * @notice Parse an unsigned integer from the view at `_index`. * @dev Requires that the view have >= `_bytes` bytes following that index. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8); } /** * @notice Parse an unsigned integer from LE bytes. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return reverseUint256(uint256(index(memView, _index, _bytes))); } /** * @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes * following that index. * @param memView The view * @param _index The index * @return address - The address */ function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) { return address(uint160(indexUint(memView, _index, 20))); } /** * @notice Return the keccak256 hash of the underlying memory * @param memView The view * @return digest - The keccak256 hash of the underlying memory */ function keccak(bytes29 memView) internal pure returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly digest := keccak256(_loc, _len) } } /** * @notice Return the sha2 digest of the underlying memory. * @dev We explicitly deallocate memory afterwards. * @param memView The view * @return digest - The sha2 hash of the underlying memory */ function sha2(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 digest := mload(ptr) } } /** * @notice Implements bitcoin's hash160 (rmd160(sha2())) * @param memView The pre-image * @return digest - the Digest */ function hash160(bytes29 memView) internal view returns (bytes20 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160 digest := mload(add(ptr, 0xc)) // return value is 0-prefixed. } } /** * @notice Implements bitcoin's hash256 (double sha2) * @param memView A view of the preimage * @return digest - the Digest */ function hash256(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2 digest := mload(ptr) } } /** * @notice Return true if the underlying memory is equal. Else false. * @param left The first view * @param right The second view * @return bool - True if the underlying memory is equal */ function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right); } /** * @notice Return false if the underlying memory is equal. Else true. * @param left The first view * @param right The second view * @return bool - False if the underlying memory is equal */ function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !untypedEqual(left, right); } /** * @notice Compares type equality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are the same */ function equal(bytes29 left, bytes29 right) internal pure returns (bool) { return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right)); } /** * @notice Compares type inequality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are not the same */ function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !equal(left, right); } /** * @notice Copy the view to a location, return an unsafe memory reference * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memView The view * @param _newLoc The new location * @return written - the unsafe memory reference */ function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) { require(notNull(memView), "TypedMemView/copyTo - Null pointer deref"); require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref"); uint256 _len = len(memView); uint256 _oldLoc = loc(memView); uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message } // use the identity precompile to copy // guaranteed not to fail, so pop the success pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len)) } written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len); } /** * @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to * the new memory * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param memView The view * @return ret - The view pointing to the new memory */ function clone(bytes29 memView) internal view returns (bytes memory ret) { uint256 ptr; uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer ret := ptr } unsafeCopyTo(memView, ptr + 0x20); assembly { // solium-disable-previous-line security/no-inline-assembly mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer mstore(ptr, _len) // write len of new array (in bytes) } } /** * @notice Join the views in memory, return an unsafe reference to the memory. * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memViews The views * @return unsafeView - The conjoined view pointing to the new memory */ function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) { assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _location) { revert(0x60, 0x20) // empty revert message } } uint256 _offset = 0; for (uint256 i = 0; i < memViews.length; i ++) { bytes29 memView = memViews[i]; unsafeCopyTo(memView, _location + _offset); _offset += len(memView); } unsafeView = unsafeBuildUnchecked(0, _location, _offset); } /** * @notice Produce the keccak256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The keccak256 digest */ function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return keccak(unsafeJoin(memViews, ptr)); } /** * @notice Produce the sha256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The sha256 digest */ function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return sha2(unsafeJoin(memViews, ptr)); } /** * @notice copies all views, joins them into a new bytearray. * @param memViews The views * @return ret - The new byte array */ function join(bytes29[] memory memViews) internal view returns (bytes memory ret) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } bytes29 _newView = unsafeJoin(memViews, ptr + 0x20); uint256 _written = len(_newView); uint256 _footprint = footprint(_newView); assembly { // solium-disable-previous-line security/no-inline-assembly // store the legnth mstore(ptr, _written) // new pointer is old + 0x20 + the footprint of the body mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; library Encoding { // ============ Constants ============ bytes private constant NIBBLE_LOOKUP = "0123456789abcdef"; // ============ Internal Functions ============ /** * @notice Encode a uint32 in its DECIMAL representation, with leading * zeroes. * @param _num The number to encode * @return _encoded The encoded number, suitable for use in abi. * encodePacked */ function decimalUint32(uint32 _num) internal pure returns (uint80 _encoded) { uint80 ASCII_0 = 0x30; // all over/underflows are impossible // this will ALWAYS produce 10 decimal characters for (uint8 i = 0; i < 10; i += 1) { _encoded |= ((_num % 10) + ASCII_0) << (i * 8); _num = _num / 10; } } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * @param _bytes The 32 bytes as uint256 * @return _firstHalf The top 16 bytes * @return _secondHalf The bottom 16 bytes */ function encodeHex(uint256 _bytes) internal pure returns (uint256 _firstHalf, uint256 _secondHalf) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _firstHalf |= _byteHex(_b); if (i != 16) { _firstHalf <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _secondHalf |= _byteHex(_b); if (i != 0) { _secondHalf <<= 16; } } } /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _byte The byte * @return _char The encoded hex character */ function _nibbleHex(uint8 _byte) private pure returns (uint8 _char) { uint8 _nibble = _byte & 0x0f; // keep bottom 4, 0 top 4 _char = uint8(NIBBLE_LOOKUP[_nibble]); } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _byte The byte * @return _encoded The hex-encoded byte */ function _byteHex(uint8 _byte) private pure returns (uint16 _encoded) { _encoded |= _nibbleHex(_byte >> 4); // top 4 bits _encoded <<= 8; _encoded |= _nibbleHex(_byte); // lower 4 bits } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /** * @title UpgradeBeaconProxy * @notice * Proxy contract which delegates all logic, including initialization, * to an implementation contract. * The implementation contract is stored within an Upgrade Beacon contract; * the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract. * The Upgrade Beacon contract for this Proxy is immutably specified at deployment. * @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage * found in 0age's implementation: * https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol * With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment * found in OpenZeppelin's implementation: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol */ contract UpgradeBeaconProxy { // ============ Immutables ============ // Upgrade Beacon address is immutable (therefore not kept in contract storage) address private immutable upgradeBeacon; // ============ Constructor ============ /** * @notice Validate that the Upgrade Beacon is a contract, then set its * address immutably within this contract. * Validate that the implementation is also a contract, * Then call the initialization function defined at the implementation. * The deployment will revert and pass along the * revert reason if the initialization function reverts. * @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract * @param _initializationCalldata Calldata supplied when calling the initialization function */ constructor(address _upgradeBeacon, bytes memory _initializationCalldata) payable { // Validate the Upgrade Beacon is a contract require(Address.isContract(_upgradeBeacon), "beacon !contract"); // set the Upgrade Beacon upgradeBeacon = _upgradeBeacon; // Validate the implementation is a contract address _implementation = _getImplementation(_upgradeBeacon); require( Address.isContract(_implementation), "beacon implementation !contract" ); // Call the initialization function on the implementation if (_initializationCalldata.length > 0) { _initialize(_implementation, _initializationCalldata); } } // ============ External Functions ============ /** * @notice Forwards all calls with data to _fallback() * No public functions are declared on the contract, so all calls hit fallback */ fallback() external payable { _fallback(); } /** * @notice Forwards all calls with no data to _fallback() */ receive() external payable { _fallback(); } // ============ Private Functions ============ /** * @notice Call the initialization function on the implementation * Used at deployment to initialize the proxy * based on the logic for initialization defined at the implementation * @param _implementation - Contract to which the initalization is delegated * @param _initializationCalldata - Calldata supplied when calling the initialization function */ function _initialize( address _implementation, bytes memory _initializationCalldata ) private { // Delegatecall into the implementation, supplying initialization calldata. (bool _ok, ) = _implementation.delegatecall(_initializationCalldata); // Revert and include revert data if delegatecall to implementation reverts. if (!_ok) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } /** * @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon */ function _fallback() private { _delegate(_getImplementation()); } /** * @notice Delegate function execution to the implementation contract * @dev This is a low level function that doesn't return to its internal * call site. It will return whatever is returned by the implementation to the * external caller, reverting and returning the revert data if implementation * reverts. * @param _implementation - Address to which the function execution is delegated */ function _delegate(address _implementation) private { 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()) // Delegatecall to the implementation, supplying calldata and gas. // Out and outsize are set to zero - instead, use the return buffer. let result := delegatecall( gas(), _implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data from the return buffer. returndatacopy(0, 0, returndatasize()) switch result // Delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @return _implementation Address of the current implementation. */ function _getImplementation() private view returns (address _implementation) { _implementation = _getImplementation(upgradeBeacon); } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @dev _upgradeBeacon is passed as a parameter so that * we can also use this function in the constructor, * where we can't access immutable variables. * @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation * @return _implementation Address of the current implementation. */ function _getImplementation(address _upgradeBeacon) private view returns (address _implementation) { // Get the current implementation address from the upgrade beacon. (bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(_ok, string(_returnData)); // Set the implementation to the address returned from the upgrade beacon. _implementation = abi.decode(_returnData, (address)); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @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; require(c / _a == _b, "Overflow during multiplication."); 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) { require(_b <= _a, "Underflow during subtraction."); 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, "Overflow during addition."); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Message} from "../libs/Message.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title Common * @author Celo Labs Inc. * @notice Shared utilities between Home and Replica. */ abstract contract Common is Initializable { // ============ Enums ============ // States: // 0 - UnInitialized - before initialize function is called // note: the contract is initialized at deploy time, so it should never be in this state // 1 - Active - as long as the contract has not become fraudulent // 2 - Failed - after a valid fraud proof has been submitted; // contract will no longer accept updates or new messages enum States { UnInitialized, Active, Failed } // ============ Immutable Variables ============ // Domain of chain on which the contract is deployed uint32 public immutable localDomain; // ============ Public Variables ============ // Address of bonded Updater address public updater; // Current state of contract States public state; // The latest root that has been signed by the Updater bytes32 public committedRoot; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[47] private __GAP; // ============ Events ============ /** * @notice Emitted when update is made on Home * or unconfirmed update root is submitted on Replica * @param homeDomain Domain of home contract * @param oldRoot Old merkle root * @param newRoot New merkle root * @param signature Updater's signature on `oldRoot` and `newRoot` */ event Update( uint32 indexed homeDomain, bytes32 indexed oldRoot, bytes32 indexed newRoot, bytes signature ); /** * @notice Emitted when proof of a double update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root shared between two conflicting updates * @param newRoot Array containing two conflicting new roots * @param signature Signature on `oldRoot` and `newRoot`[0] * @param signature2 Signature on `oldRoot` and `newRoot`[1] */ event DoubleUpdate( bytes32 oldRoot, bytes32[2] newRoot, bytes signature, bytes signature2 ); // ============ Modifiers ============ /** * @notice Ensures that contract state != FAILED when the function is called */ modifier notFailed() { require(state != States.Failed, "failed state"); _; } // ============ Constructor ============ constructor(uint32 _localDomain) { localDomain = _localDomain; } // ============ Initializer ============ function __Common_initialize(address _updater) internal initializer { updater = _updater; state = States.Active; } // ============ External Functions ============ /** * @notice Called by external agent. Checks that signatures on two sets of * roots are valid and that the new roots conflict with each other. If both * cases hold true, the contract is failed and a `DoubleUpdate` event is * emitted. * @dev When `fail()` is called on Home, updater is slashed. * @param _oldRoot Old root shared between two conflicting updates * @param _newRoot Array containing two conflicting new roots * @param _signature Signature on `_oldRoot` and `_newRoot`[0] * @param _signature2 Signature on `_oldRoot` and `_newRoot`[1] */ function doubleUpdate( bytes32 _oldRoot, bytes32[2] calldata _newRoot, bytes calldata _signature, bytes calldata _signature2 ) external notFailed { if ( Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) && Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) && _newRoot[0] != _newRoot[1] ) { _fail(); emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view virtual returns (bytes32); // ============ Internal Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" * @param _homeDomain the Home domain to hash */ function _homeDomainHash(uint32 _homeDomain) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_homeDomain, "OPTICS")); } /** * @notice Set contract state to FAILED * @dev Called when a valid fraud proof is submitted */ function _setFailed() internal { state = States.Failed; } /** * @notice Moves the contract into failed state * @dev Called when fraud is proven * (Double Update is submitted on Home or Replica, * or Improper Update is submitted on Home) */ function _fail() internal virtual; /** * @notice Checks that signature was signed by Updater * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Signature on `_oldRoot` and `_newRoot` * @return TRUE iff signature is valid signed by updater **/ function _isUpdaterSignature( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) internal view returns (bool) { bytes32 _digest = keccak256( abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return (ECDSA.recover(_digest, _signature) == updater); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title QueueLib * @author Celo Labs Inc. * @notice Library containing queue struct and operations for queue used by * Home and Replica. **/ library QueueLib { /** * @notice Queue struct * @dev Internally keeps track of the `first` and `last` elements through * indices and a mapping of indices to enqueued elements. **/ struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; } /** * @notice Initializes the queue * @dev Empty state denoted by _q.first > q._last. Queue initialized * with _q.first = 1 and _q.last = 0. **/ function initialize(Queue storage _q) internal { if (_q.first == 0) { _q.first = 1; } } /** * @notice Enqueues a single new element * @param _item New element to be enqueued * @return _last Index of newly enqueued element **/ function enqueue(Queue storage _q, bytes32 _item) internal returns (uint128 _last) { _last = _q.last + 1; _q.last = _last; if (_item != bytes32(0)) { // saves gas if we're queueing 0 _q.queue[_last] = _item; } } /** * @notice Dequeues element at front of queue * @dev Removes dequeued element from storage * @return _item Dequeued element **/ function dequeue(Queue storage _q) internal returns (bytes32 _item) { uint128 _last = _q.last; uint128 _first = _q.first; require(_length(_last, _first) != 0, "Empty"); _item = _q.queue[_first]; if (_item != bytes32(0)) { // saves gas if we're dequeuing 0 delete _q.queue[_first]; } _q.first = _first + 1; } /** * @notice Batch enqueues several elements * @param _items Array of elements to be enqueued * @return _last Index of last enqueued element **/ function enqueue(Queue storage _q, bytes32[] memory _items) internal returns (uint128 _last) { _last = _q.last; for (uint256 i = 0; i < _items.length; i += 1) { _last += 1; bytes32 _item = _items[i]; if (_item != bytes32(0)) { _q.queue[_last] = _item; } } _q.last = _last; } /** * @notice Batch dequeues `_number` elements * @dev Reverts if `_number` > queue length * @param _number Number of elements to dequeue * @return Array of dequeued elements **/ function dequeue(Queue storage _q, uint256 _number) internal returns (bytes32[] memory) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted require(_length(_last, _first) >= _number, "Insufficient"); bytes32[] memory _items = new bytes32[](_number); for (uint256 i = 0; i < _number; i++) { _items[i] = _q.queue[_first]; delete _q.queue[_first]; _first++; } _q.first = _first; return _items; } /** * @notice Returns true if `_item` is in the queue and false if otherwise * @dev Linearly scans from _q.first to _q.last looking for `_item` * @param _item Item being searched for in queue * @return True if `_item` currently exists in queue, false if otherwise **/ function contains(Queue storage _q, bytes32 _item) internal view returns (bool) { for (uint256 i = _q.first; i <= _q.last; i++) { if (_q.queue[i] == _item) { return true; } } return false; } /// @notice Returns last item in queue /// @dev Returns bytes32(0) if queue empty function lastItem(Queue storage _q) internal view returns (bytes32) { return _q.queue[_q.last]; } /// @notice Returns element at front of queue without removing element /// @dev Reverts if queue is empty function peek(Queue storage _q) internal view returns (bytes32 _item) { require(!isEmpty(_q), "Empty"); _item = _q.queue[_q.first]; } /// @notice Returns true if queue is empty and false if otherwise function isEmpty(Queue storage _q) internal view returns (bool) { return _q.last < _q.first; } /// @notice Returns number of elements in queue function length(Queue storage _q) internal view returns (uint256) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted return _length(_last, _first); } /// @notice Returns number of elements between `_last` and `_first` (used internally) function _length(uint128 _last, uint128 _first) internal pure returns (uint256) { return uint256(_last + 1 - _first); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // work based on eth2 deposit contract, which is used under CC0-1.0 /** * @title MerkleLib * @author Celo Labs Inc. * @notice An incremental merkle tree modeled on the eth2 deposit contract. **/ library MerkleLib { uint256 internal constant TREE_DEPTH = 32; uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1; /** * @notice Struct representing incremental merkle tree. Contains current * branch and the number of inserted leaves in the tree. **/ struct Tree { bytes32[TREE_DEPTH] branch; uint256 count; } /** * @notice Inserts `_node` into merkle tree * @dev Reverts if tree is full * @param _node Element to insert into tree **/ function insert(Tree storage _tree, bytes32 _node) internal { require(_tree.count < MAX_LEAVES, "merkle tree full"); _tree.count += 1; uint256 size = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { if ((size & 1) == 1) { _tree.branch[i] = _node; return; } _node = keccak256(abi.encodePacked(_tree.branch[i], _node)); size /= 2; } // As the loop should always end prematurely with the `return` statement, // this code should be unreachable. We assert `false` just to be safe. assert(false); } /** * @notice Calculates and returns`_tree`'s current root given array of zero * hashes * @param _zeroes Array of zero hashes * @return _current Calculated root of `_tree` **/ function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes) internal view returns (bytes32 _current) { uint256 _index = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _tree.branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _zeroes[i])); } } } /// @notice Calculates and returns`_tree`'s current root function root(Tree storage _tree) internal view returns (bytes32) { return rootWithCtx(_tree, zeroHashes()); } /// @notice Returns array of TREE_DEPTH zero hashes /// @return _zeroes Array of TREE_DEPTH zero hashes function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes) { _zeroes[0] = Z_0; _zeroes[1] = Z_1; _zeroes[2] = Z_2; _zeroes[3] = Z_3; _zeroes[4] = Z_4; _zeroes[5] = Z_5; _zeroes[6] = Z_6; _zeroes[7] = Z_7; _zeroes[8] = Z_8; _zeroes[9] = Z_9; _zeroes[10] = Z_10; _zeroes[11] = Z_11; _zeroes[12] = Z_12; _zeroes[13] = Z_13; _zeroes[14] = Z_14; _zeroes[15] = Z_15; _zeroes[16] = Z_16; _zeroes[17] = Z_17; _zeroes[18] = Z_18; _zeroes[19] = Z_19; _zeroes[20] = Z_20; _zeroes[21] = Z_21; _zeroes[22] = Z_22; _zeroes[23] = Z_23; _zeroes[24] = Z_24; _zeroes[25] = Z_25; _zeroes[26] = Z_26; _zeroes[27] = Z_27; _zeroes[28] = Z_28; _zeroes[29] = Z_29; _zeroes[30] = Z_30; _zeroes[31] = Z_31; } /** * @notice Calculates and returns the merkle root for the given leaf * `_item`, a merkle branch, and the index of `_item` in the tree. * @param _item Merkle leaf * @param _branch Merkle proof * @param _index Index of `_item` in tree * @return _current Calculated merkle root **/ function branchRoot( bytes32 _item, bytes32[TREE_DEPTH] memory _branch, uint256 _index ) internal pure returns (bytes32 _current) { _current = _item; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _next)); } } } // keccak256 zero hashes bytes32 internal constant Z_0 = hex"0000000000000000000000000000000000000000000000000000000000000000"; bytes32 internal constant Z_1 = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; bytes32 internal constant Z_2 = hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"; bytes32 internal constant Z_3 = hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85"; bytes32 internal constant Z_4 = hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344"; bytes32 internal constant Z_5 = hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d"; bytes32 internal constant Z_6 = hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968"; bytes32 internal constant Z_7 = hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83"; bytes32 internal constant Z_8 = hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af"; bytes32 internal constant Z_9 = hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0"; bytes32 internal constant Z_10 = hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5"; bytes32 internal constant Z_11 = hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892"; bytes32 internal constant Z_12 = hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c"; bytes32 internal constant Z_13 = hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb"; bytes32 internal constant Z_14 = hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc"; bytes32 internal constant Z_15 = hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2"; bytes32 internal constant Z_16 = hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f"; bytes32 internal constant Z_17 = hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a"; bytes32 internal constant Z_18 = hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0"; bytes32 internal constant Z_19 = hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0"; bytes32 internal constant Z_20 = hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2"; bytes32 internal constant Z_21 = hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9"; bytes32 internal constant Z_22 = hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377"; bytes32 internal constant Z_23 = hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652"; bytes32 internal constant Z_24 = hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef"; bytes32 internal constant Z_25 = hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d"; bytes32 internal constant Z_26 = hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0"; bytes32 internal constant Z_27 = hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e"; bytes32 internal constant Z_28 = hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e"; bytes32 internal constant Z_29 = hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322"; bytes32 internal constant Z_30 = hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735"; bytes32 internal constant Z_31 = hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9"; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import { TypeCasts } from "./TypeCasts.sol"; /** * @title Message Library * @author Celo Labs Inc. * @notice Library for formatted messages used by Home and Replica. **/ library Message { using TypedMemView for bytes; using TypedMemView for bytes29; // Number of bytes in formatted message before `body` field uint256 internal constant PREFIX_LENGTH = 76; /** * @notice Returns formatted (packed) message with provided fields * @param _originDomain Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce * @param _destinationDomain Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes of message body * @return Formatted message **/ function formatMessage( uint32 _originDomain, bytes32 _sender, uint32 _nonce, uint32 _destinationDomain, bytes32 _recipient, bytes memory _messageBody ) internal pure returns (bytes memory) { return abi.encodePacked( _originDomain, _sender, _nonce, _destinationDomain, _recipient, _messageBody ); } /** * @notice Returns leaf of formatted message with provided fields. * @param _origin Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce number * @param _destination Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _body Raw bytes of message body * @return Leaf (hash) of formatted message **/ function messageHash( uint32 _origin, bytes32 _sender, uint32 _nonce, uint32 _destination, bytes32 _recipient, bytes memory _body ) internal pure returns (bytes32) { return keccak256( formatMessage( _origin, _sender, _nonce, _destination, _recipient, _body ) ); } /// @notice Returns message's origin field function origin(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(0, 4)); } /// @notice Returns message's sender field function sender(bytes29 _message) internal pure returns (bytes32) { return _message.index(4, 32); } /// @notice Returns message's nonce field function nonce(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(36, 4)); } /// @notice Returns message's destination field function destination(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(40, 4)); } /// @notice Returns message's recipient field as bytes32 function recipient(bytes29 _message) internal pure returns (bytes32) { return _message.index(44, 32); } /// @notice Returns message's recipient field as an address function recipientAddress(bytes29 _message) internal pure returns (address) { return TypeCasts.bytes32ToAddress(recipient(_message)); } /// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) function body(bytes29 _message) internal pure returns (bytes29) { return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0); } function leaf(bytes29 _message) internal view returns (bytes32) { return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message))); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {MerkleLib} from "../libs/Merkle.sol"; /** * @title MerkleTreeManager * @author Celo Labs Inc. * @notice Contains a Merkle tree instance and * exposes view functions for the tree. */ contract MerkleTreeManager { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; MerkleLib.Tree public tree; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Public Functions ============ /** * @notice Calculates and returns tree's current root */ function root() public view returns (bytes32) { return tree.root(); } /** * @notice Returns the number of inserted leaves in the tree (current index) */ function count() public view returns (uint256) { return tree.count; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {QueueLib} from "../libs/Queue.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title QueueManager * @author Celo Labs Inc. * @notice Contains a queue instance and * exposes view functions for the queue. **/ contract QueueManager is Initializable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; QueueLib.Queue internal queue; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Initializer ============ function __QueueManager_initialize() internal initializer { queue.initialize(); } // ============ Public Functions ============ /** * @notice Returns number of elements in queue */ function queueLength() external view returns (uint256) { return queue.length(); } /** * @notice Returns TRUE iff `_item` is in the queue */ function queueContains(bytes32 _item) external view returns (bool) { return queue.contains(_item); } /** * @notice Returns last item enqueued to the queue */ function queueEnd() external view returns (bytes32) { return queue.lastItem(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IUpdaterManager { function slashUpdater(address payable _reporter) external; function updater() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library TypeCasts { using TypedMemView for bytes; using TypedMemView for bytes29; function coerceBytes32(string memory _s) internal pure returns (bytes32 _b) { _b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length)); } // treat it as a null-terminated string of max 32 bytes function coerceString(bytes32 _buf) internal pure returns (string memory _newStr) { uint8 _slen = 0; while (_slen < 32 && _buf[_slen] != 0) { _slen++; } // solhint-disable-next-line no-inline-assembly assembly { _newStr := mload(0x40) mstore(0x40, add(_newStr, 0x40)) // may end up with extra mstore(_newStr, _slen) mstore(add(_newStr, 0x20), _buf) } } // alignment preserving cast function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } // alignment preserving cast function bytes32ToAddress(bytes32 _buf) internal pure returns (address) { return address(uint160(uint256(_buf))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol"; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; /** * @title Replica * @author Celo Labs Inc. * @notice Track root updates on Home, * prove and dispatch messages to end recipients. */ contract Replica is Version0, Common { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; using TypedMemView for bytes; using TypedMemView for bytes29; using Message for bytes29; // ============ Enums ============ // Status of Message: // 0 - None - message has not been proven or processed // 1 - Proven - message inclusion proof has been validated // 2 - Processed - message has been dispatched to recipient enum MessageStatus { None, Proven, Processed } // ============ Immutables ============ // Minimum gas for message processing uint256 public immutable PROCESS_GAS; // Reserved gas (to ensure tx completes in case message processing runs out) uint256 public immutable RESERVE_GAS; // ============ Public Storage ============ // Domain of home chain uint32 public remoteDomain; // Number of seconds to wait before root becomes confirmable uint256 public optimisticSeconds; // re-entrancy guard uint8 private entered; // Mapping of roots to allowable confirmation times mapping(bytes32 => uint256) public confirmAt; // Mapping of message leaves to MessageStatus mapping(bytes32 => MessageStatus) public messages; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[44] private __GAP; // ============ Events ============ /** * @notice Emitted when message is processed * @param messageHash Hash of message that failed to process * @param success TRUE if the call was executed successfully, FALSE if the call reverted * @param returnData the return data from the external call */ event Process( bytes32 indexed messageHash, bool indexed success, bytes indexed returnData ); // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor( uint32 _localDomain, uint256 _processGas, uint256 _reserveGas ) Common(_localDomain) { require(_processGas >= 850_000, "!process gas"); require(_reserveGas >= 15_000, "!reserve gas"); PROCESS_GAS = _processGas; RESERVE_GAS = _reserveGas; } // ============ Initializer ============ function initialize( uint32 _remoteDomain, address _updater, bytes32 _committedRoot, uint256 _optimisticSeconds ) public initializer { __Common_initialize(_updater); entered = 1; remoteDomain = _remoteDomain; committedRoot = _committedRoot; confirmAt[_committedRoot] = 1; optimisticSeconds = _optimisticSeconds; } // ============ External Functions ============ /** * @notice Called by external agent. Submits the signed update's new root, * marks root's allowable confirmation time, and emits an `Update` event. * @dev Reverts if update doesn't build off latest committedRoot * or if signature is invalid. * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Updater's signature on `_oldRoot` and `_newRoot` */ function update( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // ensure that update is building off the last submitted root require(_oldRoot == committedRoot, "not current update"); // validate updater signature require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); // Hook for future use _beforeUpdate(); // set the new root's confirmation timer confirmAt[_newRoot] = block.timestamp + optimisticSeconds; // update committedRoot committedRoot = _newRoot; emit Update(remoteDomain, _oldRoot, _newRoot, _signature); } /** * @notice First attempts to prove the validity of provided formatted * `message`. If the message is successfully proven, then tries to process * message. * @dev Reverts if `prove` call returns false * @param _message Formatted message (refer to Common.sol Message library) * @param _proof Merkle proof of inclusion for message's leaf * @param _index Index of leaf in home's merkle tree */ function proveAndProcess( bytes memory _message, bytes32[32] calldata _proof, uint256 _index ) external { require(prove(keccak256(_message), _proof, _index), "!prove"); process(_message); } /** * @notice Given formatted message, attempts to dispatch * message payload to end recipient. * @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol) * Reverts if formatted message's destination domain is not the Replica's domain, * if message has not been proven, * or if not enough gas is provided for the dispatch transaction. * @param _message Formatted message * @return _success TRUE iff dispatch transaction succeeded */ function process(bytes memory _message) public returns (bool _success) { bytes29 _m = _message.ref(0); // ensure message was meant for this domain require(_m.destination() == localDomain, "!destination"); // ensure message has been proven bytes32 _messageHash = _m.keccak(); require(messages[_messageHash] == MessageStatus.Proven, "!proven"); // check re-entrancy guard require(entered == 1, "!reentrant"); entered = 0; // update message status as processed messages[_messageHash] = MessageStatus.Processed; // A call running out of gas TYPICALLY errors the whole tx. We want to // a) ensure the call has a sufficient amount of gas to make a // meaningful state change. // b) ensure that if the subcall runs out of gas, that the tx as a whole // does not revert (i.e. we still mark the message processed) // To do this, we require that we have enough gas to process // and still return. We then delegate only the minimum processing gas. require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas"); // get the message recipient address _recipient = _m.recipientAddress(); // set up for assembly call uint256 _toCopy; uint256 _maxCopy = 256; uint256 _gas = PROCESS_GAS; // allocate memory for returndata bytes memory _returnData = new bytes(_maxCopy); bytes memory _calldata = abi.encodeWithSignature( "handle(uint32,bytes32,bytes)", _m.origin(), _m.sender(), _m.body().clone() ); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _recipient, // recipient 0, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } // emit process results emit Process(_messageHash, _success, _returnData); // reset re-entrancy guard entered = 1; } // ============ Public Functions ============ /** * @notice Check that the root has been submitted * and that the optimistic timeout period has expired, * meaning the root can be processed * @param _root the Merkle root, submitted in an update, to check * @return TRUE iff root has been submitted & timeout has expired */ function acceptableRoot(bytes32 _root) public view returns (bool) { uint256 _time = confirmAt[_root]; if (_time == 0) { return false; } return block.timestamp >= _time; } /** * @notice Attempts to prove the validity of message given its leaf, the * merkle proof of inclusion for the leaf, and the index of the leaf. * @dev Reverts if message's MessageStatus != None (i.e. if message was * already proven or processed) * @dev For convenience, we allow proving against any previous root. * This means that witnesses never need to be updated for the new root * @param _leaf Leaf of message to prove * @param _proof Merkle proof of inclusion for leaf * @param _index Index of leaf in home's merkle tree * @return Returns true if proof was valid and `prove` call succeeded **/ function prove( bytes32 _leaf, bytes32[32] calldata _proof, uint256 _index ) public returns (bool) { // ensure that message has not been proven or processed require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None"); // calculate the expected root based on the proof bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index); // if the root is valid, change status to Proven if (acceptableRoot(_calculatedRoot)) { messages[_leaf] = MessageStatus.Proven; return true; } return false; } /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(remoteDomain); } // ============ Internal Functions ============ /** * @notice Moves the contract into failed state * @dev Called when a Double Update is submitted */ function _fail() internal override { _setFailed(); } /// @notice Hook for potential future use // solhint-disable-next-line no-empty-blocks function _beforeUpdate() internal {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IMessageRecipient { function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external; } // 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 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; } }
Return the memory address of the underlying bytes. memView The view return _loc - The memory address/ solium-disable-previous-line security/no-inline-assembly 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space)
function loc(bytes29 memView) internal pure returns (uint96 _loc) { assembly { _loc := and(shr(120, memView), _mask) } }
1,209,360
./partial_match/1/0x8ea429bB80F88f1fBB75653A5Eb7f5CFbD73B3f2/sources/RootalaBranch.sol
creat a new Rootala_Branch_Contractadd this contract to branchers archiveset twig for lastBranch:count branchScore :count how much submited for all times:Branch Number:
function deployBranch( address _bOne, address _bTwo, address _bThree, address _bFour, address _bFive, address _bSix, address _bSeven, address _bEight )internal pausable{ require(usedAddresses[msg.sender] != true , " you are brancher !!! "); require(RootalaBranch(_bEight).score() < 5 , "last branch is full"); RootalaBranch rootalaBranch = new RootalaBranch(msg.sender,_bOne,_bTwo,_bThree,_bFour,_bFive,_bSix,_bSeven,_bEight); rootalaBranches[msg.sender] = address(rootalaBranch); usedAddresses[msg.sender] = true; RootalaBranch(_bEight).setTwig(address(rootalaBranch)); branchScore[_bOne] ++; branchScore[_bTwo] ++; branchScore[_bThree] ++; branchScore[_bFour] ++; branchScore[_bFive] ++; branchScore[_bSix] ++; branchScore[_bSeven] ++; branchScore[_bEight] ++; countBranchs ++; branchNumber[address(rootalaBranch)] = countBranchs; emit newBranch(_bEight,address(rootalaBranch),branchPrice()); }
15,627,883
./full_match/4/0xa9c685Af2e781aD8840a7648542727668f99e2C3/sources/browser/TFG.sol
Funcion para validar un certificado
function ValidaCert (string memory _RefCert, string memory _DNI) public view returns(bool){ bool validez = false; if(Certificados[_RefCert].HashDNI == keccak256(abi.encodePacked(_DNI))){ validez = true; } return validez; }
649,633
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./ERC721A_M.sol"; import "./meltable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; ///////////////////////////////////////////////////////////////////////////////////////////////////// // // // ooo ooooo .oooooo. .oooooo..o .o. ooooo .oooooo. .oooooo. // // `88. .888' d8P' `Y8b d8P' `Y8 .888. `888' d8P' `Y8b d8P' `Y8b // // 888b d'888 888 888 Y88bo. .8"888. 888 888 888 888 // // 8 Y88. .P 888 888 888 `"Y8888o. .8' `888. 888 888 888 888 // // 8 `888' 888 888 888 `"Y88b .88ooo8888. 888 888 888 888 // // 8 Y 888 `88b d88' oo .d8P .8' `888. 888 `88b ooo `88b d88' // // o8o o888o `Y8bood8P' 8""88888P' o88o o8888o o888o `Y8bood8P' `Y8bood8P' // // // ///////////////////////////////////////////////////////////////////////////////////////////////////// contract MosaicoBrasileiro is ERC721A_M, IERC721Receiver, Ownable, Meltable { /// ================================ /// ============ Errors ============ /// ================================ error NonexistentToken(); error AlreadyMinted(); error WrongNFT(); error NotMosaicOwner(); error NotOwnerOfAll(); error NotAuthorized(); /// ================================= /// ============ Storage ============ /// ================================= address private immutable mosaicNftAddress; address private immutable slicerAddress; string private baseURI; /// ===================================== /// ============ Constructor ============ /// ===================================== constructor( string memory baseURI_, address slicerAddress_, address mosaicNftAddress_ ) ERC721A_M("MosaicoBrasileiro2022", "MOSAICO") { baseURI = baseURI_; slicerAddress = slicerAddress_; mosaicNftAddress = mosaicNftAddress_; } /// =================================== /// ============ Functions ============ /// =================================== /** * @notice Mints the 16 NFTs to an address. * * @dev Can only be called if the NFTs haven't been minted yet */ function mint(address to) private { if (totalSupply() != 0) revert AlreadyMinted(); _safeMint(to, 16); } /** * @notice Burns the 16 NFTs and sends the mosaic NFT to the msg.sender. * * @dev Can only be called if the msg.sender owns all the 16 NFTs and this address owns the mosaic NFT. */ function melt() external { if (balanceOf(msg.sender) != 16) revert NotOwnerOfAll(); _burnAll(); IERC721(mosaicNftAddress).safeTransferFrom(address(this), msg.sender, 1); _currentIndex = 1; } /** * @notice Safeguard function to mint the entire collection to an address who transferred * the mosaic NFT using `transferFrom`, instead of `safeTransferFrom` or `claimToMint` * * @dev Can only be by contract owner */ function emergencyMint(address previousOwner) external onlyOwner { if (IERC721(mosaicNftAddress).balanceOf(address(this)) == 0) revert NotMosaicOwner(); mint(previousOwner); } /** * @notice Mints 16 NFTs to the sender, in exchange for storing the mosaic NFT. * * @dev NFT owner needs to have approved this contract address as operator for the mosaic contract. * @dev One of the two ways to claim the entire collection, the other one being calling safeTransferFrom. */ function sendAndMint() external { if (IERC721(mosaicNftAddress).balanceOf(msg.sender) == 0) revert NotMosaicOwner(); IERC721(mosaicNftAddress).safeTransferFrom(msg.sender, address(this), 1); } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. */ function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @notice ERC-2981 implementation * * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) { if (!_exists(tokenId)) revert NonexistentToken(); return (slicerAddress, salePrice / 10); } /** * @notice Mints 16 nfts to the sender of the mosaic NFT. * * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address from, uint256 tokenId, bytes memory ) external virtual override returns (bytes4) { if (msg.sender != mosaicNftAddress) revert WrongNFT(); if (tokenId != 1) revert WrongNFT(); mint(from); return this.onERC721Received.selector; } }
Mints 16 NFTs to the sender, in exchange for storing the mosaic NFT. NFT owner needs to have approved this contract address as operator for the mosaic contract. One of the two ways to claim the entire collection, the other one being calling safeTransferFrom./
function sendAndMint() external { if (IERC721(mosaicNftAddress).balanceOf(msg.sender) == 0) revert NotMosaicOwner(); IERC721(mosaicNftAddress).safeTransferFrom(msg.sender, address(this), 1); }
12,622,375
./partial_match/1/0x5E482759e7d5846f03c34cA4a6a0e7e8c2bf2Cd7/sources/KOAM.sol
Total supply of tokens return The total supply/
function totalSupply() external pure override returns (uint256) { return totalTokenSupply; }
16,026,959
./partial_match/1/0x715F06DA4bB270bD6924014dee44172834Cb219D/sources/contracts/rewards/FarmingRange.sol
in case of reward update, return reward diff and refund user if needed _rewardIndex the number of the phase to update _endBlock new endblock of the phase _rewardPerBlock new rewardPerBlock of the phase rewardInfo pointer on the array of rewardInfo in storage campaign pointer on the campaign in storage selectedRewardInfo pointer on the selectedRewardInfo in storage return refund_ boolean, true if user got refund return diff_ the reward difference/
function _updateRewardsDiff( uint256 _rewardIndex, uint256 _endBlock, uint256 _rewardPerBlock, RewardInfo[] storage rewardInfo, CampaignInfo storage campaign, RewardInfo storage selectedRewardInfo ) internal virtual returns (bool refund_, uint256 diff_) { uint256 _previousStartBlock = _rewardIndex == 0 ? campaign.startBlock : rewardInfo[_rewardIndex - 1].endBlock; uint256 _newStartBlock = block.number > _previousStartBlock ? block.number : _previousStartBlock; uint256 _previousBlockRange = selectedRewardInfo.endBlock - _previousStartBlock; uint256 _newBlockRange = _endBlock - _newStartBlock; uint256 _selectedRewardPerBlock = selectedRewardInfo.rewardPerBlock; uint256 _accumulatedRewards = (_newStartBlock - _previousStartBlock) * _selectedRewardPerBlock; uint256 _previousTotalRewards = _selectedRewardPerBlock * _previousBlockRange; uint256 _totalRewards = _rewardPerBlock * _newBlockRange; refund_ = _previousTotalRewards > _totalRewards + _accumulatedRewards; diff_ = refund_ ? _previousTotalRewards - _totalRewards - _accumulatedRewards : _totalRewards + _accumulatedRewards - _previousTotalRewards; if (refund_) { campaign.rewardToken.safeTransfer(rewardManager, diff_); } }
9,390,845
pragma solidity ^0.5.2; // File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol interface intvoteinterface31 { //inject NONSTANDARD NAMING //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier ONLYPROPOSALOWNER70(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING modifier VOTABLE14(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING event NEWPROPOSAL82( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event EXECUTEPROPOSAL67(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VOTEPROPOSAL81( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CANCELPROPOSAL59(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING event CANCELVOTING5(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING function PROPOSE48( //inject NONSTANDARD NAMING uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns(bytes32); function VOTE79( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns(bool); function CANCELVOTE62(bytes32 _proposalId) external; //inject NONSTANDARD NAMING function GETNUMBEROFCHOICES23(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function ISVOTABLE72(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING function ISABSTAINALLOW86() external pure returns(bool); //inject NONSTANDARD NAMING function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol interface ierc2016 { //inject NONSTANDARD NAMING function TRANSFER74(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE55(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM94(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY28() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF62(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE21(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL97(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol interface votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function BURNREPUTATION8(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function STAKINGTOKENTRANSFER23(ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING external returns(bool); function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol contract ownable56 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED0(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED0(address(0), _owner); } function OWNER8() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER65() { //inject NONSTANDARD NAMING require(ISOWNER85()); _; } function ISOWNER85() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP94() public ONLYOWNER65 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED0(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP25(address newOwner) public ONLYOWNER65 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP15(newOwner); } function _TRANSFEROWNERSHIP15(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED0(_owner, newOwner); _owner = newOwner; } } // File: @daostack/infra/contracts/Reputation.sol contract reputation51 is ownable56 { //inject NONSTANDARD NAMING uint8 public decimals = 18; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event MINT64(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING // Event indicating burning of reputation for an address. event BURN4(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of reputation at a specific block number uint128 value; } // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // Tracks the history of the `totalSupply` of the reputation Checkpoint[] totalSupplyHistory; constructor( ) public { } function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING return TOTALSUPPLYAT94(block.number); } // Query balance and totalSupply in History function BALANCEOF62(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return BALANCEOFAT72(_owner, block.number); } function BALANCEOFAT72(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING public view returns (uint256) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; // This will return the expected balance during normal situations } else { return GETVALUEAT9(balances[_owner], _blockNumber); } } function TOTALSUPPLYAT94(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return GETVALUEAT9(totalSupplyHistory, _blockNumber); } } function MINT38(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY28(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = BALANCEOF62(_user); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply + _amount); UPDATEVALUEATNOW85(balances[_user], previousBalanceTo + _amount); emit MINT64(_user, _amount); return true; } function BURN49(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY28(); uint256 amountBurned = _amount; uint256 previousBalanceFrom = BALANCEOF62(_user); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply - amountBurned); UPDATEVALUEATNOW85(balances[_user], previousBalanceFrom - amountBurned); emit BURN4(_user, amountBurned); return true; } // Internal helper functions to query and set a value in a snapshot array function GETVALUEAT9(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING if (checkpoints.length == 0) { return 0; } // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function UPDATEVALUEATNOW85(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING require(uint128(_value) == _value); //check value is in the 128 bits bounderies if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol library safemath4 { //inject NONSTANDARD NAMING function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV25(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB37(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD40(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol contract erc2045 is ierc2016 { //inject NONSTANDARD NAMING using safemath4 for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF62(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE21(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER74(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER44(msg.sender, to, value); return true; } function APPROVE55(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL97(msg.sender, spender, value); return true; } function TRANSFERFROM94(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB37(value); _TRANSFER44(from, to, value); emit APPROVAL97(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE67(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD40(addedValue); emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE11(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB37(subtractedValue); emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER44(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB37(value); _balances[to] = _balances[to].ADD40(value); emit TRANSFER49(from, to, value); } function _MINT14(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD40(value); _balances[account] = _balances[account].ADD40(value); emit TRANSFER49(address(0), account, value); } function _BURN11(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB37(value); _balances[account] = _balances[account].SUB37(value); emit TRANSFER49(account, address(0), value); } function _BURNFROM86(address account, uint256 value) internal { //inject NONSTANDARD NAMING _allowed[account][msg.sender] = _allowed[account][msg.sender].SUB37(value); _BURN11(account, value); emit APPROVAL97(account, msg.sender, _allowed[account][msg.sender]); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol contract erc20burnable16 is erc2045 { //inject NONSTANDARD NAMING function BURN49(uint256 value) public { //inject NONSTANDARD NAMING _BURN11(msg.sender, value); } function BURNFROM98(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM86(from, value); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/DAOToken.sol contract daotoken36 is erc2045, erc20burnable16, ownable56 { //inject NONSTANDARD NAMING string public name; string public symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals61 = 18; //inject NONSTANDARD NAMING uint256 public cap; constructor(string memory _name, string memory _symbol, uint256 _cap) public { name = _name; symbol = _symbol; cap = _cap; } function MINT38(address _to, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING if (cap > 0) require(TOTALSUPPLY28().ADD40(_amount) <= cap); _MINT14(_to, _amount); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol library address8 { //inject NONSTANDARD NAMING function ISCONTRACT13(address account) internal view returns (bool) { //inject NONSTANDARD NAMING uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: /Users/oren/daostack/daostack2/daostack/contracts/libs/SafeERC20.sol pragma solidity ^0.5.2; library safeerc2019 { //inject NONSTANDARD NAMING using address8 for address; bytes4 constant private transfer_selector2 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private transferfrom_selector45 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private approve_selector67 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING function SAFETRANSFER100(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transfer_selector2, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFETRANSFERFROM10(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transferfrom_selector45, _from, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFEAPPROVE78(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. require((_value == 0) || (ierc2016(_erc20Addr).ALLOWANCE21(msg.sender, _spender) == 0)); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(approve_selector67, _spender, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/Avatar.sol contract avatar70 is ownable56 { //inject NONSTANDARD NAMING using safeerc2019 for address; string public orgName; daotoken36 public nativeToken; reputation51 public nativeReputation; event GENERICCALL1(address indexed _contract, bytes _params, bool _success); //inject NONSTANDARD NAMING event SENDETHER8(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFER37(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFERFROM36(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENAPPROVAL0(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING event RECEIVEETHER12(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING constructor(string memory _orgName, daotoken36 _nativeToken, reputation51 _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } function() external payable { emit RECEIVEETHER12(msg.sender, msg.value); } function GENERICCALL24(address _contract, bytes memory _data) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool success, bytes memory returnValue) { // solhint-disable-next-line avoid-low-level-calls (success, returnValue) = _contract.call(_data); emit GENERICCALL1(_contract, _data, success); } function SENDETHER91(uint256 _amountInWei, address payable _to) public ONLYOWNER65 returns(bool) { //inject NONSTANDARD NAMING _to.transfer(_amountInWei); emit SENDETHER8(_amountInWei, _to); return true; } function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool) { address(_externalToken).SAFETRANSFER100(_to, _value); emit EXTERNALTOKENTRANSFER37(address(_externalToken), _to, _value); return true; } function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING ierc2016 _externalToken, address _from, address _to, uint256 _value ) public ONLYOWNER65 returns(bool) { address(_externalToken).SAFETRANSFERFROM10(_from, _to, _value); emit EXTERNALTOKENTRANSFERFROM36(address(_externalToken), _from, _to, _value); return true; } function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool) { address(_externalToken).SAFEAPPROVE78(_spender, _value); emit EXTERNALTOKENAPPROVAL0(address(_externalToken), _spender, _value); return true; } } // File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalSchemeInterface.sol contract universalschemeinterface23 { //inject NONSTANDARD NAMING function UPDATEPARAMETERS61(bytes32 _hashedParameters) public; //inject NONSTANDARD NAMING function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/globalConstraints/GlobalConstraintInterface.sol contract globalconstraintinterface55 { //inject NONSTANDARD NAMING enum CallPhase { Pre, Post, PreAndPost } function PRE44( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function POST41( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function WHEN71() public returns(CallPhase); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/ControllerInterface.sol interface controllerinterface59 { //inject NONSTANDARD NAMING function MINTREPUTATION65(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function BURNREPUTATION8(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function MINTTOKENS53(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REGISTERSCHEME80(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSCHEME15(address _scheme, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSELF18(address _avatar) external returns(bool); //inject NONSTANDARD NAMING function ADDGLOBALCONSTRAINT70(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REMOVEGLOBALCONSTRAINT6 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UPGRADECONTROLLER96(address _newController, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function GENERICCALL24(address _contract, bytes calldata _data, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool, bytes memory); function SENDETHER91(uint256 _amountInWei, address payable _to, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING ierc2016 _externalToken, address _from, address _to, uint256 _value, avatar70 _avatar) external returns(bool); function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function GETNATIVEREPUTATION64(address _avatar) //inject NONSTANDARD NAMING external view returns(address); function ISSCHEMEREGISTERED53( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING function GETSCHEMEPARAMETERS80(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETGLOBALCONSTRAINTPARAMETERS50(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETSCHEMEPERMISSIONS72(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING function GLOBALCONSTRAINTSCOUNT61(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING function ISGLOBALCONSTRAINTREGISTERED65(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalScheme.sol contract universalscheme48 is ownable56, universalschemeinterface23 { //inject NONSTANDARD NAMING bytes32 public hashedParameters; // For other parameters. function UPDATEPARAMETERS61( //inject NONSTANDARD NAMING bytes32 _hashedParameters ) public ONLYOWNER65 { hashedParameters = _hashedParameters; } function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING require(controllerinterface59(_avatar.OWNER8()).ISSCHEMEREGISTERED53(address(this), address(_avatar)), "scheme is not registered"); return controllerinterface59(_avatar.OWNER8()).GETSCHEMEPARAMETERS80(address(this), address(_avatar)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol library ecdsa86 { //inject NONSTANDARD NAMING function RECOVER59(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } function TOETHSIGNEDMESSAGEHASH91(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/libs/RealMath.sol library realmath32 { //inject NONSTANDARD NAMING uint256 constant private real_bits92 = 256; //inject NONSTANDARD NAMING uint256 constant private real_fbits8 = 40; //inject NONSTANDARD NAMING uint256 constant private real_one87 = uint256(1) << real_fbits8; //inject NONSTANDARD NAMING function POW66(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 tempRealBase = realBase; uint256 tempExponent = exponent; // Start with the 0th power uint256 realResult = real_one87; while (tempExponent != 0) { // While there are still bits set if ((tempExponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base realResult = MUL16(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; // Do the squaring tempRealBase = MUL16(tempRealBase, tempRealBase); } // Return the final result. return uint216(realResult / real_one87); } function FRACTION6(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV25(uint256(numerator) * real_one87, uint256(denominator) * real_one87); } function MUL16(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. return uint256((uint256(realA) * uint256(realB)) >> real_fbits8); } function DIV25(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return uint256((uint256(realNumerator) * real_one87) / uint256(realDenominator)); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol interface proposalexecuteinterface9 { //inject NONSTANDARD NAMING function EXECUTEPROPOSAL85(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/SafeMath.sol // File: openzeppelin-solidity/contracts/math/Math.sol library math46 { //inject NONSTANDARD NAMING function MAX19(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE32(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol contract genesisprotocollogic61 is intvoteinterface31 { //inject NONSTANDARD NAMING using safemath4 for uint; using math46 for uint; using realmath32 for uint216; using realmath32 for uint256; using address8 for address; enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod} enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed} //Organization's parameters struct Parameters { uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar. uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode. uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode. uint256 preBoostedVotePeriodLimit; //the time limit for a proposal //to be in an preparation state (stable) before boosted. uint256 thresholdConst; //constant for threshold calculation . //threshold =thresholdConst ** (numberOfBoostedProposals) uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals //in the threshold calculation to prevent overflow uint256 quietEndingPeriod; //quite ending period uint256 proposingRepReward;//proposer reputation reward. uint256 votersReputationLossRatio;//Unsuccessful pre booster //voters lose votersReputationLossRatio% of their reputation. uint256 minimumDaoBounty; uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula //(daoBountyConst * averageBoostDownstakes)/100 . uint256 activationTime;//the point in time after which proposals can be created. //if this address is set so only this address is allowed to vote of behalf of someone else. address voteOnBehalf; } struct Voter { uint256 vote; // YES(1) ,NO(2) uint256 reputation; // amount of voter's reputation bool preBoosted; } struct Staker { uint256 vote; // YES(1) ,NO(2) uint256 amount; // amount of staker's stake uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation. } struct Proposal { bytes32 organizationId; // the organization unique identifier the proposal is target to. address callbacks; // should fulfill voting callbacks interface. ProposalState state; uint256 winningVote; //the winning vote. address proposer; //the proposal boosted period limit . it is updated for the case of quiteWindow mode. uint256 currentBoostedVotePeriodLimit; bytes32 paramsHash; uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time. uint256 daoBounty; uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers. uint256 confidenceThreshold; //The percentage from upper stakes which the caller for the expiration was given. uint256 expirationCallBountyPercentage; uint[3] times; //times[0] - submittedTime //times[1] - boostedPhaseTime //times[2] -preBoostedPhaseTime; // vote reputation mapping(uint256 => uint256 ) votes; // vote reputation mapping(uint256 => uint256 ) preBoostedVotes; // address voter mapping(address => Voter ) voters; // vote stakes mapping(uint256 => uint256 ) stakes; // address staker mapping(address => Staker ) stakers; } event STAKE61(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _staker, uint256 _vote, uint256 _amount ); event REDEEM77(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMDAOBOUNTY80(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMREPUTATION31(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event STATECHANGE55(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING event GPEXECUTEPROPOSAL49(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING event EXPIRATIONCALLBOUNTY13(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. mapping(bytes32=>uint) public orgBoostedProposalsCnt; //organizationId => organization mapping(bytes32 => address ) public organizations; //organizationId => averageBoostDownstakes mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted; uint256 constant public num_of_choices20 = 2; //inject NONSTANDARD NAMING uint256 constant public no97 = 2; //inject NONSTANDARD NAMING uint256 constant public yes52 = 1; //inject NONSTANDARD NAMING uint256 public proposalsCnt; // Total number of proposals ierc2016 public stakingToken; address constant private gen_token_address24 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING uint256 constant private max_boosted_proposals66 = 4096; //inject NONSTANDARD NAMING constructor(ierc2016 _stakingToken) public { //The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS . //This will work for a network which already hosted the GEN token on this address (e.g mainnet). //If such contract address does not exist in the network (e.g ganache) //the contract will use the _stakingToken param as the //staking token address. if (address(gen_token_address24).ISCONTRACT13()) { stakingToken = ierc2016(gen_token_address24); } else { stakingToken = _stakingToken; } } modifier VOTABLE14(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(_ISVOTABLE26(_proposalId)); _; } function PROPOSE48(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING external returns(bytes32) { // solhint-disable-next-line not-rely-on-time require(now > parameters[_paramsHash].activationTime, "not active yet"); //Check parameters existence. require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt = proposalsCnt.ADD40(1); // Open proposal: Proposal memory proposal; proposal.callbacks = msg.sender; proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization)); proposal.state = ProposalState.Queued; // solhint-disable-next-line not-rely-on-time proposal.times[0] = now;//submitted time proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit; proposal.proposer = _proposer; proposal.winningVote = no97; proposal.paramsHash = _paramsHash; if (organizations[proposal.organizationId] == address(0)) { if (_organization == address(0)) { organizations[proposal.organizationId] = msg.sender; } else { organizations[proposal.organizationId] = _organization; } } //calc dao bounty uint256 daoBounty = parameters[_paramsHash].daoBountyConst.MUL16(averagesDownstakesOfBoosted[proposal.organizationId]).DIV25(100); if (daoBounty < parameters[_paramsHash].minimumDaoBounty) { proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty; } else { proposal.daoBountyRemain = daoBounty; } proposal.totalStakes = proposal.daoBountyRemain; proposals[proposalId] = proposal; proposals[proposalId].stakes[no97] = proposal.daoBountyRemain;//dao downstake on the proposal Staker storage staker = proposals[proposalId].stakers[organizations[proposal.organizationId]]; staker.vote = no97; staker.amount = proposal.daoBountyRemain; emit NEWPROPOSAL82(proposalId, organizations[proposal.organizationId], num_of_choices20, _proposer, _paramsHash); return proposalId; } function EXECUTEBOOSTED98(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Boosted); require(_EXECUTE0(_proposalId), "proposal need to expire"); uint256 expirationCallBountyPercentage = // solhint-disable-next-line not-rely-on-time (uint(1).ADD40(now.SUB37(proposal.currentBoostedVotePeriodLimit.ADD40(proposal.times[1])).DIV25(15))); if (expirationCallBountyPercentage > 100) { expirationCallBountyPercentage = 100; } proposal.expirationCallBountyPercentage = expirationCallBountyPercentage; expirationCallBounty = expirationCallBountyPercentage.MUL16(proposal.stakes[yes52]).DIV25(100); require(stakingToken.TRANSFER74(msg.sender, expirationCallBounty), "transfer to msg.sender failed"); emit EXPIRATIONCALLBOUNTY13(_proposalId, msg.sender, expirationCallBounty); } function SETPARAMETERS19( //inject NONSTANDARD NAMING uint[11] calldata _params, //use array here due to stack too deep issue. address _voteOnBehalf ) external returns(bytes32) { require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100"); require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000"); require(_params[7] <= 100, "votersReputationLossRatio <= 100"); require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod"); require(_params[8] > 0, "minimumDaoBounty should be > 0"); require(_params[9] > 0, "daoBountyConst should be > 0"); bytes32 paramsHash = GETPARAMETERSHASH35(_params, _voteOnBehalf); //set a limit for power for a given alpha to prevent overflow uint256 limitExponent = 172;//for alpha less or equal 2 uint256 j = 2; for (uint256 i = 2000; i < 16000; i = i*2) { if ((_params[4] > i) && (_params[4] <= i*2)) { limitExponent = limitExponent/j; break; } j++; } parameters[paramsHash] = Parameters({ queuedVoteRequiredPercentage: _params[0], queuedVotePeriodLimit: _params[1], boostedVotePeriodLimit: _params[2], preBoostedVotePeriodLimit: _params[3], thresholdConst:uint216(_params[4]).FRACTION6(uint216(1000)), limitExponentValue:limitExponent, quietEndingPeriod: _params[5], proposingRepReward: _params[6], votersReputationLossRatio:_params[7], minimumDaoBounty:_params[8], daoBountyConst:_params[9], activationTime:_params[10], voteOnBehalf:_voteOnBehalf }); return paramsHash; } // solhint-disable-next-line function-max-lines,code-complexity function REDEEM91(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue), "Proposal should be Executed or ExpiredInQueue"); Parameters memory params = parameters[proposal.paramsHash]; uint256 lostReputation; if (proposal.winningVote == yes52) { lostReputation = proposal.preBoostedVotes[no97]; } else { lostReputation = proposal.preBoostedVotes[yes52]; } lostReputation = (lostReputation.MUL16(params.votersReputationLossRatio))/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; if (staker.amount > 0) { if (proposal.state == ProposalState.ExpiredInQueue) { //Stakes of a proposal that expires in Queue are sent back to stakers rewards[0] = staker.amount; } else if (staker.vote == proposal.winningVote) { uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; uint256 totalStakes = proposal.stakes[yes52].ADD40(proposal.stakes[no97]); if (staker.vote == yes52) { uint256 _totalStakes = ((totalStakes.MUL16(100 - proposal.expirationCallBountyPercentage))/100) - proposal.daoBounty; rewards[0] = (staker.amount.MUL16(_totalStakes))/totalWinningStakes; } else { rewards[0] = (staker.amount.MUL16(totalStakes))/totalWinningStakes; if (organizations[proposal.organizationId] == _beneficiary) { //dao redeem it reward rewards[0] = rewards[0].SUB37(proposal.daoBounty); } } } staker.amount = 0; } //as voter Voter storage voter = proposal.voters[_beneficiary]; if ((voter.reputation != 0) && (voter.preBoosted)) { if (proposal.state == ProposalState.ExpiredInQueue) { //give back reputation for the voter rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100); } else if (proposal.winningVote == voter.vote) { uint256 preBoostedVotes = proposal.preBoostedVotes[yes52].ADD40(proposal.preBoostedVotes[no97]); rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100) .ADD40((voter.reputation.MUL16(lostReputation))/preBoostedVotes); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes52)&&(proposal.proposer != address(0))) { rewards[2] = params.proposingRepReward; proposal.proposer = address(0); } if (rewards[0] != 0) { proposal.totalStakes = proposal.totalStakes.SUB37(rewards[0]); require(stakingToken.TRANSFER74(_beneficiary, rewards[0]), "transfer to beneficiary failed"); emit REDEEM77(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]); } if (rewards[1].ADD40(rewards[2]) != 0) { votingmachinecallbacksinterface79(proposal.callbacks) .MINTREPUTATION65(rewards[1].ADD40(rewards[2]), _beneficiary, _proposalId); emit REDEEMREPUTATION31( _proposalId, organizations[proposal.organizationId], _beneficiary, rewards[1].ADD40(rewards[2]) ); } } function REDEEMDAOBOUNTY7(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING public returns(uint256 redeemedAmount, uint256 potentialAmount) { Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Executed); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; Staker storage staker = proposal.stakers[_beneficiary]; if ( (staker.amount4Bounty > 0)&& (staker.vote == proposal.winningVote)&& (proposal.winningVote == yes52)&& (totalWinningStakes != 0)) { //as staker potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes; } if ((potentialAmount != 0)&& (votingmachinecallbacksinterface79(proposal.callbacks) .BALANCEOFSTAKINGTOKEN17(stakingToken, _proposalId) >= potentialAmount)) { staker.amount4Bounty = 0; proposal.daoBountyRemain = proposal.daoBountyRemain.SUB37(potentialAmount); require( votingmachinecallbacksinterface79(proposal.callbacks) .STAKINGTOKENTRANSFER23(stakingToken, _beneficiary, potentialAmount, _proposalId)); redeemedAmount = potentialAmount; emit REDEEMDAOBOUNTY80(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount); } } function SHOULDBOOST32(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING Proposal memory proposal = proposals[_proposalId]; return (_SCORE65(_proposalId) > THRESHOLD35(proposal.paramsHash, proposal.organizationId)); } function THRESHOLD35(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING uint256 power = orgBoostedProposalsCnt[_organizationId]; Parameters storage params = parameters[_paramsHash]; if (power > params.limitExponentValue) { power = params.limitExponentValue; } return params.thresholdConst.POW66(power); } function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING uint[11] memory _params,//use array here due to stack too deep issue. address _voteOnBehalf ) public pure returns(bytes32) { //double call to keccak256 to avoid deep stack issue when call with too many params. return keccak256( abi.encodePacked( keccak256( abi.encodePacked( _params[0], _params[1], _params[2], _params[3], _params[4], _params[5], _params[6], _params[7], _params[8], _params[9], _params[10]) ), _voteOnBehalf )); } // solhint-disable-next-line function-max-lines,code-complexity function _EXECUTE0(bytes32 _proposalId) internal VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint256 totalReputation = votingmachinecallbacksinterface79(proposal.callbacks).GETTOTALREPUTATIONSUPPLY93(_proposalId); //first divide by 100 to prevent overflow uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage; ExecutionState executionState = ExecutionState.None; uint256 averageDownstakesOfBoosted; uint256 confidenceThreshold; if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. if (proposal.state == ProposalState.Queued) { executionState = ExecutionState.QueueBarCrossed; } else if (proposal.state == ProposalState.PreBoosted) { executionState = ExecutionState.PreBoostedBarCrossed; } else { executionState = ExecutionState.BoostedBarCrossed; } proposal.state = ProposalState.Executed; } else { if (proposal.state == ProposalState.Queued) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) { proposal.state = ProposalState.ExpiredInQueue; proposal.winningVote = no97; executionState = ExecutionState.QueueTimeOut; } else { confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId); if (_SCORE65(_proposalId) > confidenceThreshold) { //change proposal mode to PreBoosted mode. proposal.state = ProposalState.PreBoosted; // solhint-disable-next-line not-rely-on-time proposal.times[2] = now; proposal.confidenceThreshold = confidenceThreshold; } } } if (proposal.state == ProposalState.PreBoosted) { confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId); // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) { if ((_SCORE65(_proposalId) > confidenceThreshold) && (orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals66)) { //change proposal mode to Boosted mode. proposal.state = ProposalState.Boosted; // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; orgBoostedProposalsCnt[proposal.organizationId]++; //add a value to average -> average = average + ((value - average) / nbValues) averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; // solium-disable-next-line indentation averagesDownstakesOfBoosted[proposal.organizationId] = uint256(int256(averageDownstakesOfBoosted) + ((int256(proposal.stakes[no97])-int256(averageDownstakesOfBoosted))/ int256(orgBoostedProposalsCnt[proposal.organizationId]))); } } else { //check the Confidence level is stable uint256 proposalScore = _SCORE65(_proposalId); if (proposalScore <= proposal.confidenceThreshold.MIN92(confidenceThreshold)) { proposal.state = ProposalState.Queued; } else if (proposal.confidenceThreshold > proposalScore) { proposal.confidenceThreshold = confidenceThreshold; } } } } if ((proposal.state == ProposalState.Boosted) || (proposal.state == ProposalState.QuietEndingPeriod)) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) { proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedTimeOut; } } if (executionState != ExecutionState.None) { if ((executionState == ExecutionState.BoostedTimeOut) || (executionState == ExecutionState.BoostedBarCrossed)) { orgBoostedProposalsCnt[tmpProposal.organizationId] = orgBoostedProposalsCnt[tmpProposal.organizationId].SUB37(1); //remove a value from average = ((average * nbValues) - value) / (nbValues - 1); uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId]; if (boostedProposals == 0) { averagesDownstakesOfBoosted[proposal.organizationId] = 0; } else { averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; averagesDownstakesOfBoosted[proposal.organizationId] = (averageDownstakesOfBoosted.MUL16(boostedProposals+1).SUB37(proposal.stakes[no97]))/boostedProposals; } } emit EXECUTEPROPOSAL67( _proposalId, organizations[proposal.organizationId], proposal.winningVote, totalReputation ); emit GPEXECUTEPROPOSAL49(_proposalId, executionState); proposalexecuteinterface9(proposal.callbacks).EXECUTEPROPOSAL85(_proposalId, int(proposal.winningVote)); proposal.daoBounty = proposal.daoBountyRemain; } if (tmpProposal.state != proposal.state) { emit STATECHANGE55(_proposalId, proposal.state); } return (executionState != ExecutionState.None); } function _STAKE17(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING // 0 is not a valid vote. require(_vote <= num_of_choices20 && _vote > 0, "wrong vote value"); require(_amount > 0, "staking amount should be >0"); if (_EXECUTE0(_proposalId)) { return true; } Proposal storage proposal = proposals[_proposalId]; if ((proposal.state != ProposalState.PreBoosted) && (proposal.state != ProposalState.Queued)) { return false; } // enable to increase stake only on the previous stake vote Staker storage staker = proposal.stakers[_staker]; if ((staker.amount > 0) && (staker.vote != _vote)) { return false; } uint256 amount = _amount; require(stakingToken.TRANSFERFROM94(_staker, address(this), amount), "fail transfer from staker"); proposal.totalStakes = proposal.totalStakes.ADD40(amount); //update totalRedeemableStakes staker.amount = staker.amount.ADD40(amount); //This is to prevent average downstakes calculation overflow //Note that any how GEN cap is 100000000 ether. require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high"); require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high"); if (_vote == yes52) { staker.amount4Bounty = staker.amount4Bounty.ADD40(amount); } staker.vote = _vote; proposal.stakes[_vote] = amount.ADD40(proposal.stakes[_vote]); emit STAKE61(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount); return _EXECUTE0(_proposalId); } // solhint-disable-next-line function-max-lines,code-complexity function INTERNALVOTE44(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING require(_vote <= num_of_choices20 && _vote > 0, "0 < _vote <= 2"); if (_EXECUTE0(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint256 reputation = votingmachinecallbacksinterface79(proposal.callbacks).REPUTATIONOF100(_voter, _proposalId); require(reputation > 0, "_voter must have reputation"); require(reputation >= _rep, "reputation >= _rep"); uint256 rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, return false. if (proposal.voters[_voter].reputation != 0) { return false; } // The voting itself: proposal.votes[_vote] = rep.ADD40(proposal.votes[_vote]); //check if the current winningVote changed or there is a tie. //for the case there is a tie the current winningVote set to NO. if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) || ((proposal.votes[no97] == proposal.votes[proposal.winningVote]) && proposal.winningVote == yes52)) { if (proposal.state == ProposalState.Boosted && // solhint-disable-next-line not-rely-on-time ((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))|| proposal.state == ProposalState.QuietEndingPeriod) { //quietEndingPeriod if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) }); if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) { proposal.preBoostedVotes[_vote] = rep.ADD40(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.MUL16(rep))/100; votingmachinecallbacksinterface79(proposal.callbacks).BURNREPUTATION8(reputationDeposit, _voter, _proposalId); } emit VOTEPROPOSAL81(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _EXECUTE0(_proposalId); } function _SCORE65(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; //proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal. return proposal.stakes[yes52]/proposal.stakes[no97]; } function _ISVOTABLE26(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol contract genesisprotocol36 is intvoteinterface31, genesisprotocollogic61 { //inject NONSTANDARD NAMING using ecdsa86 for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant delegation_hash_eip71264 = //inject NONSTANDARD NAMING keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce constructor(ierc2016 _stakingToken) public // solhint-disable-next-line no-empty-blocks genesisprotocollogic61(_stakingToken) { } function STAKE3(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING return _STAKE17(_proposalId, _vote, _amount, msg.sender); } function STAKEWITHSIGNATURE10( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( delegation_hash_eip71264, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).TOETHSIGNEDMESSAGEHASH91(); } address staker = delegationDigest.RECOVER59(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].ADD40(1); return _STAKE17(_proposalId, _vote, _amount, staker); } function VOTE79(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING external VOTABLE14(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return INTERNALVOTE44(_proposalId, voter, _vote, _amount); } function CANCELVOTE62(bytes32 _proposalId) external VOTABLE14(_proposalId) { //inject NONSTANDARD NAMING //this is not allowed return; } function EXECUTE34(bytes32 _proposalId) external VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING return _EXECUTE0(_proposalId); } function GETNUMBEROFCHOICES23(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING return num_of_choices20; } function GETPROPOSALTIMES43(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING return proposals[_proposalId].times; } function VOTEINFO83(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].votes[_choice]; } function ISVOTABLE72(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING return _ISVOTABLE26(_proposalId); } function PROPOSALSTATUS51(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING return ( proposals[_proposalId].preBoostedVotes[yes52], proposals[_proposalId].preBoostedVotes[no97], proposals[_proposalId].stakes[yes52], proposals[_proposalId].stakes[no97] ); } function GETPROPOSALORGANIZATION83(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING return (proposals[_proposalId].organizationId); } function GETSTAKER73(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } function VOTESTAKE72(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].stakes[_vote]; } function WINNINGVOTE73(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].winningVote; } function STATE40(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING return proposals[_proposalId].state; } function ISABSTAINALLOW86() external pure returns(bool) { //inject NONSTANDARD NAMING return false; } function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING return (yes52, no97); } function SCORE19(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING return _SCORE65(_proposalId); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/votingMachines/VotingMachineCallbacks.sol contract votingmachinecallbacks93 is votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING struct ProposalInfo { uint256 blockNumber; // the proposal's block number avatar70 avatar; // the proposal's avatar address votingMachine; } modifier ONLYVOTINGMACHINE57(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(msg.sender == proposalsInfo[_proposalId].votingMachine, "only VotingMachine"); _; } //proposalId -> ProposalInfo mapping(bytes32 => ProposalInfo ) public proposalsInfo; function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).MINTREPUTATION65(_amount, _beneficiary, address(avatar)); } function BURNREPUTATION8(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).BURNREPUTATION8(_amount, _beneficiary, address(avatar)); } function STAKINGTOKENTRANSFER23( //inject NONSTANDARD NAMING ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).EXTERNALTOKENTRANSFER67(_stakingToken, _beneficiary, _amount, avatar); } function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING avatar70 avatar = proposalsInfo[_proposalId].avatar; if (proposalsInfo[_proposalId].avatar == avatar70(0)) { return 0; } return _stakingToken.BALANCEOF62(address(avatar)); } function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[_proposalId]; if (proposal.avatar == avatar70(0)) { return 0; } return proposal.avatar.nativeReputation().TOTALSUPPLYAT94(proposal.blockNumber); } function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[_proposalId]; if (proposal.avatar == avatar70(0)) { return 0; } return proposal.avatar.nativeReputation().BALANCEOFAT72(_owner, proposal.blockNumber); } } // File: contracts/universalSchemes/GenericScheme.sol contract genericscheme3 is universalscheme48, votingmachinecallbacks93, proposalexecuteinterface9 { //inject NONSTANDARD NAMING event NEWCALLPROPOSAL18( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, bytes _callData, string _descriptionHash ); event PROPOSALEXECUTED2( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, bytes _genericCallReturnValue ); event PROPOSALEXECUTEDBYVOTINGMACHINE53( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, int256 _param ); event PROPOSALDELETED34(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING // Details of a voting proposal: struct CallProposal { bytes callData; bool exist; bool passed; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals; struct Parameters { intvoteinterface31 intVote; bytes32 voteParams; address contractToCall; } // A mapping from hashes to parameters (use to store a particular configuration on the controller) mapping(bytes32=>Parameters) public parameters; function EXECUTEPROPOSAL85(bytes32 _proposalId, int256 _decision) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.exist, "must be a live proposal"); require(proposal.passed == false, "cannot execute twice"); if (_decision == 1) { proposal.passed = true; EXECUTE34(_proposalId); } else { delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED34(address(avatar), _proposalId); } emit PROPOSALEXECUTEDBYVOTINGMACHINE53(address(avatar), _proposalId, _decision); return true; } function EXECUTE34(bytes32 _proposalId) public { //inject NONSTANDARD NAMING avatar70 avatar = proposalsInfo[_proposalId].avatar; Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(avatar)]; CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.exist, "must be a live proposal"); require(proposal.passed, "proposal must passed by voting machine"); proposal.exist = false; bytes memory genericCallReturnValue; bool success; controllerinterface59 controller = controllerinterface59(avatar70(avatar).OWNER8()); (success, genericCallReturnValue) = controller.GENERICCALL24(params.contractToCall, proposal.callData, avatar); if (success) { delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED34(address(avatar), _proposalId); emit PROPOSALEXECUTED2(address(avatar), _proposalId, genericCallReturnValue); } else { proposal.exist = true; } } function SETPARAMETERS19( //inject NONSTANDARD NAMING bytes32 _voteParams, intvoteinterface31 _intVote, address _contractToCall ) public returns(bytes32) { bytes32 paramsHash = GETPARAMETERSHASH35(_voteParams, _intVote, _contractToCall); parameters[paramsHash].voteParams = _voteParams; parameters[paramsHash].intVote = _intVote; parameters[paramsHash].contractToCall = _contractToCall; return paramsHash; } function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING bytes32 _voteParams, intvoteinterface31 _intVote, address _contractToCall ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall)); } function PROPOSECALL64(avatar70 _avatar, bytes memory _callData, string memory _descriptionHash) //inject NONSTANDARD NAMING public returns(bytes32) { Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)]; intvoteinterface31 intVote = params.intVote; bytes32 proposalId = intVote.PROPOSE48(2, params.voteParams, msg.sender, address(_avatar)); organizationsProposals[address(_avatar)][proposalId] = CallProposal({ callData: _callData, exist: true, passed: false }); proposalsInfo[proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar, votingMachine:address(params.intVote) }); emit NEWCALLPROPOSAL18(address(_avatar), proposalId, _callData, _descriptionHash); return proposalId; } function GETCONTRACTTOCALL27(avatar70 _avatar) public view returns(address) { //inject NONSTANDARD NAMING return parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)].contractToCall; } }
inject NONSTANDARD NAMING
function TOTALSUPPLYAT94(uint256 _blockNumber) public view returns(uint256) {
12,775,693
./full_match/11155111/0xC87F732C1FfCEf4A2985c1b4Cc3d00F6f163F012/sources/contracts/Contract.sol
Purchase a package and mint an NFT, staking the reward tokens. packageId ID of the selected package./ Mint NFT Send token reward Auto stake the reward tokens Increment the token ID counter
function purchasePackage(uint256 packageId) external payable notPaused nonReentrant { Package storage pack = packages[packageId]; require(msg.value >= pack.price, "Insufficient payment"); uint256 tokenId = _tokenIdCounter.current(); _mint(msg.sender, tokenId); setTokenURI(tokenId, pack.nftURI); rewardToken.transferFrom(owner(), msg.sender, pack.tokenReward); stakedRewards[msg.sender] = stakedRewards[msg.sender].add(pack.tokenReward); stakedStartTime[msg.sender] = block.timestamp; emit PackagePurchased(msg.sender, packageId, tokenId); _tokenIdCounter.increment(); }
3,788,323
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; import "./AuthorizableNoOperator.sol"; import "./interfaces/IERC20Lockable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/ITheoretics.sol"; import "./utils/ContractGuard.sol"; import "./interfaces/ITreasury.sol"; contract Master is ERC20Snapshot, AuthorizableNoOperator, ContractGuard { using SafeMath for uint256; using SafeERC20 for IERC20Lockable; using SafeERC20 for IERC20; struct UserInfo { uint256 lockToTime; uint256 chosenLockTime; address approveTransferFrom; uint256 lastSnapshotIndex; uint256 rewardEarned; uint256 withdrawRequestedInMaster; uint256 withdrawRequestedInTheory; uint256 lastStakeRequestBlock; uint256 lastWithdrawRequestBlock; uint256 gameLocked; uint256 gameLockFrom; uint256 gameLastUnlockTime; } mapping(address => UserInfo) public userInfo; IERC20Lockable private theory; IERC20Lockable private game; ITheoretics private theoretics; ITreasury private treasury; uint256 public minLockTime; uint256 public unlockedClaimPenalty; //uint256 public extraTheoryAdded; //uint256 public extraTheoryStakeRequested; //uint256 public extraTheoryWithdrawRequested; uint256 public totalStakeRequestedInTheory; uint256 public totalWithdrawRequestedInTheory; uint256 public totalWithdrawRequestedInMaster; uint256 public totalWithdrawUnclaimedInTheory; uint256 public totalGameUnclaimed; uint256 private lastInitiatePart1Epoch; uint256 private lastInitiatePart2Epoch; uint256 private lastInitiatePart1Block; uint256 private lastInitiatePart2Block; uint256 public totalGameLocked; struct MasterSnapshot { uint256 time; uint256 rewardReceived; uint256 rewardPerShare; } MasterSnapshot[] public masterHistory; address[] private whitelistedTokens; bool private emergencyUnlock; event RewardPaid(address indexed user, uint256 reward, uint256 lockAmount); event Deposit(address indexed user, uint256 amountInTheory, uint256 amountOutMaster); event Withdraw(address indexed user, uint256 amountInMaster, uint256 amountOutTheory); event WithdrawRequest(address indexed user, uint256 amountInMaster, uint256 amountOutTheory); event LockGame(address indexed to, uint256 value); event UnlockGame(address indexed to, uint256 value); //Permissions needed: game (Game) constructor(IERC20Lockable _theory, IERC20Lockable _game, ITheoretics _theoretics, ITreasury _treasury, address[] memory _whitelist) public ERC20("Master Token", "MASTER") { theory = _theory; game = _game; theoretics = _theoretics; treasury = _treasury; minLockTime = 365 days; unlockedClaimPenalty = 30 days; MasterSnapshot memory genesisSnapshot = MasterSnapshot({time : block.number, rewardReceived : 0, rewardPerShare : 0}); masterHistory.push(genesisSnapshot); whitelistedTokens = _whitelist; } //View functions //For THEORY -> MASTER (forked from https://github.com/DefiKingdoms/contracts/blob/main/contracts/Bank.sol) function theoryToMaster(uint256 _amount) public view returns (uint256) { // Gets the amount of GovernanceToken locked in the contract uint256 totalGovernanceToken = theoretics.balanceOf(address(this)).add(totalStakeRequestedInTheory); // Gets the amount of xGovernanceToken in existence uint256 totalShares = totalSupply(); // If no xGovernanceToken exists, it is 1:1 if (totalShares == 0 || totalGovernanceToken == 0) { return _amount; } // Calculates the amount of xGovernanceToken the GovernanceToken is worth. The ratio will change overtime, as xGovernanceToken is burned/minted and GovernanceToken deposited + gained from fees / withdrawn. uint256 what = _amount.mul(totalShares).div(totalGovernanceToken); return what; } //For MASTER -> THEORY (forked from https://github.com/DefiKingdoms/contracts/blob/main/contracts/Bank.sol) function masterToTheory(uint256 _share) public view returns (uint256) { // Gets the amount of GovernanceToken locked in the contract uint256 totalGovernanceToken = theoretics.balanceOf(address(this)).add(totalStakeRequestedInTheory); // Gets the amount of xGovernanceToken in existence uint256 totalShares = totalSupply(); // If no xGovernanceToken exists, it is 1:1 if (totalShares == 0 || totalGovernanceToken == 0) { return _share; } // Calculates the amount of GovernanceToken the xGovernanceToken is worth uint256 what = _share.mul(totalGovernanceToken).div(totalShares); return what; } //Snapshot // =========== Snapshot getters function latestSnapshotIndex() public view returns (uint256) { return masterHistory.length.sub(1); } function getLatestSnapshot() internal view returns (MasterSnapshot memory) { return masterHistory[latestSnapshotIndex()]; } function getLastSnapshotIndexOf(address theorist) public view returns (uint256) { return userInfo[theorist].lastSnapshotIndex; } function getLastSnapshotOf(address theorist) internal view returns (MasterSnapshot memory) { return masterHistory[getLastSnapshotIndexOf(theorist)]; } function earned(address theorist) public view returns (uint256) { uint256 latestRPS = getLatestSnapshot().rewardPerShare; uint256 storedRPS = getLastSnapshotOf(theorist).rewardPerShare; return balanceOf(theorist).mul(latestRPS.sub(storedRPS)).div(1e18).add(userInfo[theorist].rewardEarned); } function canUnlockAmountGame(address _holder) public view returns (uint256) { uint256 lockTime = game.lockTime(); UserInfo memory user = userInfo[_holder]; if (block.timestamp <= user.gameLockFrom) { return 0; } else if (block.timestamp >= user.gameLockFrom.add(lockTime)) { return user.gameLocked; } else { uint256 releaseTime = block.timestamp.sub(user.gameLastUnlockTime); uint256 numberLockTime = user.gameLockFrom.add(lockTime).sub(user.gameLastUnlockTime); return user.gameLocked.mul(releaseTime).div(numberLockTime); } } function totalCanUnlockAmountGame(address _holder) external view returns (uint256) { return game.canUnlockAmount(_holder).add(canUnlockAmountGame(_holder)); } function totalBalanceOfGame(address _holder) external view returns (uint256) { return userInfo[_holder].gameLocked.add(game.totalBalanceOf(_holder)); } function lockOfGame(address _holder) external view returns (uint256) { return game.lockOf(_holder).add(userInfo[_holder].gameLocked); } function totalLockGame() external view returns (uint256) { return totalGameLocked.add(game.totalLock()); } //Modifiers modifier updateReward(address theorist) { if (theorist != address(0)) { UserInfo memory user = userInfo[theorist]; user.rewardEarned = earned(theorist); user.lastSnapshotIndex = latestSnapshotIndex(); userInfo[theorist] = user; } _; } //Admin functions function setAdmin(uint256 lockTime, uint256 penalty, bool emergency) external onlyAuthorized { //Default: 1 year/365 days //Lock time too high. require(lockTime <= 730 days, "LT"); //730 days/2 years = length from beginning of emissions to full LTHEORY unlock. No need to be higher than that. //Penalty too high. require(penalty <= lockTime, "PT"); //No higher than lock time. minLockTime = lockTime; unlockedClaimPenalty = penalty; emergencyUnlock = emergency; } function unlockGameForUser(address account, uint256 amount) public onlyAuthorized { // First we need to unlock all tokens the address is eligible for. uint256 pendingLocked = canUnlockAmountGame(account); if (pendingLocked > 0) { _unlockGame(account, pendingLocked); } // Then unlock GAME in the Game contract uint256 pendingLockOf = game.lockOf(account); //Lock before if (pendingLockOf > game.canUnlockAmount(msg.sender)) { game.unlockForUser(account, 0); //Unlock amount naturally first. pendingLockOf = game.lockOf(account); } if(pendingLockOf > 0) { game.unlockForUser(account, amount); uint256 amountUnlocked = pendingLockOf.sub(game.lockOf(account)); //Lock before - lock after if(amount > amountUnlocked) amount = amount.sub(amountUnlocked); //Don't unlock the amount already unlocked else amount = 0; // <= 0? = 0 } // Now that that's done, we can unlock the extra amount passed in. if(amount > 0 && userInfo[account].gameLocked > 0) _unlockGame(account, amount); } //Not required as no payable function. // function transferFTM(address payable to, uint256 amount) external onlyAuthorized onlyOneBlock // { // to.transfer(amount); // } function transferToken(IERC20 _token, address to, uint256 amount) external onlyAuthorized { //Required in order move MASTER and other tokens if they get stuck in the contract. //Some security measures in place for MASTER and THEORY. require(address(_token) != address(this) || amount <= balanceOf(address(this)).sub(totalWithdrawRequestedInMaster), "AF"); //Cannot transfer more than accidental funds. //require(address(_token) != address(theory) || amount <= theory.balanceOf(address(this)).sub(totalStakeRequested.add(totalWithdrawUnclaimed)), "Cannot withdraw pending funds."); //To prevent a number of issues that crop up when extra THEORY is removed, this function as been disabled. THEORY sent here is essentially donated to MASTER if staked. Otherwise, it is out of circulation. require(address(_token) != address(theory), "MP-"); //Cannot bring down price of MASTER. require(address(_token) != address(game) || amount <= game.balanceOf(address(this)).sub(totalGameUnclaimed).sub(totalGameLocked), "AF"); //Cannot transfer more than accidental funds. //WHITELIST BEGIN (Initiated in constructor due to contract size limits) bool isInList = false; uint256 i; uint256 len = whitelistedTokens.length; for(i = 0; i < len; ++i) { if(address(_token) == whitelistedTokens[i]) { isInList = true; break; } } require(address(_token) == address(this) //MASTER || address(_token) == address(game) //GAME || isInList, "WL"); //Can only transfer whitelisted tokens. //WHITELIST END _token.safeTransfer(to, amount); } function stakeExternalTheory(uint256 amount) external onlyAuthorized onlyOneBlock { require(amount <= theory.balanceOf(address(this)).sub(totalStakeRequestedInTheory.add(totalWithdrawUnclaimedInTheory)), "PF"); //Cannot stake pending funds. if(lastInitiatePart2Epoch == theoretics.epoch() || theoretics.getCurrentWithdrawEpochs() == 0) { //extraTheoryAdded = extraTheoryAdded.add(amount); //Track extra theory that we will stake immediately. theory.safeApprove(address(theoretics), 0); theory.safeApprove(address(theoretics), amount); theoretics.stake(amount); //Stake if we already have staked this epoch or are at 0 withdraw epochs. } else { totalStakeRequestedInTheory = totalStakeRequestedInTheory.add(amount); //extraTheoryStakeRequested = extraTheoryStakeRequested.add(amount); } } //To prevent a number of issues that crop up when extra THEORY is removed, this function as been disabled. THEORY sent here is instead shared amongst the holders. // function withdrawExternalTheory(uint256 amount) external onlyAuthorized onlyOneBlock { // //This doesn't prevent all damage to people who got in after 1.0x, but it prevents a full withdrawal. // require(amount >= extraTheoryAdded, "Can't withdraw past 1.0x."); // extraTheoryAdded = extraTheoryAdded.sub(amount); //Subtract early so we don't go over max amount. // extraTheoryWithdrawRequested = extraTheoryWithdrawRequested.add(amount); // } //Internal functions function _beforeTokenTransfer(address from, address to, uint256 amount) internal updateReward(from) updateReward(to) virtual override { super._beforeTokenTransfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal virtual override { address daoFund = treasury.daoFund(); address own = owner(); UserInfo storage user = userInfo[to]; if(user.lockToTime == 0 || !(authorized[msg.sender] || own == msg.sender || daoFund == msg.sender || address(this) == msg.sender || authorized[from] || own == from || daoFund == from || address(this) == from || authorized[to] || own == to || daoFund == to || address(this) == to)) { require(user.lockToTime == 0 || user.approveTransferFrom == from, "Receiver did not approve transfer."); user.approveTransferFrom = address(0); uint256 nextTime = block.timestamp.add(minLockTime); if(nextTime > user.lockToTime) user.lockToTime = nextTime; } super._transfer(from, to, amount); } function lockGame(address _holder, uint256 _amount) internal { UserInfo storage user = userInfo[_holder]; uint256 amount = canUnlockAmountGame(_holder); if(user.gameLocked > 0) _unlockGame(_holder, amount); //Before we lock more, make sure we unlock everything we can, even if noUnlockBeforeTransfer is set. uint256 _lockFromTime = block.timestamp; user.gameLockFrom = _lockFromTime; user.gameLocked = user.gameLocked.add(_amount); totalGameLocked = totalGameLocked.add(_amount); if (user.gameLastUnlockTime < user.gameLockFrom) { user.gameLastUnlockTime = user.gameLockFrom; } emit LockGame(_holder, _amount); } function _unlockGame(address holder, uint256 amount) internal { UserInfo storage user = userInfo[holder]; require(user.gameLocked > 0, "ILT"); //Insufficient locked tokens // Make sure they aren't trying to unlock more than they have locked. if (amount > user.gameLocked) { amount = user.gameLocked; } // If the amount is greater than the total balance, set it to max. if (amount > totalGameLocked) { amount = totalGameLocked; } game.safeTransfer(holder, amount); user.gameLocked = user.gameLocked.sub(amount); user.gameLastUnlockTime = block.timestamp; totalGameLocked = totalGameLocked.sub(amount); emit UnlockGame(holder, amount); } function _claimGame() internal { uint256 reward = userInfo[msg.sender].rewardEarned; if (reward > 0) { userInfo[msg.sender].rewardEarned = 0; totalGameUnclaimed = totalGameUnclaimed.sub(reward); // GAME can always be locked. uint256 lockAmount = 0; uint256 lockPercentage = theoretics.getLockPercentage(); require(lockPercentage <= 100, "LP"); //Invalid lock percentage, check Theoretics contract. lockAmount = reward.mul(lockPercentage).div(100); //if(lockAmount > 0) game.lock(msg.sender, lockAmount); //Due to security measures, this won't work. We have to make separate LGAME. lockGame(msg.sender, lockAmount); game.safeTransfer(msg.sender, reward.sub(lockAmount)); emit RewardPaid(msg.sender, reward, lockAmount); } } function _initiatePart1(bool allowEmergency) internal { //Unlock all LGAME, transfer GAME, then relock at normal rate. uint256 initialBalance = game.totalBalanceOf(address(this)); //uint256 _withdrawLockupEpochs = theoretics.withdrawLockupEpochs(); //uint256 _rewardLockupEpochs = theoretics.rewardLockupEpochs(); //uint256 _pegMaxUnlock = theoretics.pegMaxUnlock(); //theoretics.setLockUp(0, 0, _pegMaxUnlock); //Can't use these because of onlyOneBlock. //We may have had a saving grace: But we do have a saving grace: farm.getLockPercentage(). If that is at 95%, then we have 0 lockups. //But I was TOO anal about security: The function returns 0 after the pool ends, no matter what. //Instead, we must limit claiming and staking to every getCurrentWithdrawEpochs() epochs with a window of 5 hours and 30 minutes (you can request at any time, but it will execute once after this window). //Instead of withdrawing/claiming from theoretics here, we store withdraw requests and withdraw the full amount for everybody at once after 5 hours and 30 minutes. //If there are no withdraw requests, just claim and stake instead of withdrawing and staking. If there are no claim/withdraw requests, just stake. If there are no stake requests, fail the function. //The user can then come back at any time after to receive their withdraw/claim. //If getCurrentWithdrawEpochs() is 0, just call the initiator function immediately. if(totalWithdrawRequestedInMaster != 0) { //Burn requested master so price remains the same. _burn(address(this), totalWithdrawRequestedInMaster); totalWithdrawRequestedInMaster = 0; } if(totalWithdrawRequestedInTheory //.add(extraTheoryWithdrawRequested) == 0) theoretics.claimReward(); else { uint256 initialBalanceTheory = theory.balanceOf(address(this)); uint256 what = totalWithdrawRequestedInTheory //.add(extraTheoryWithdrawRequested); ; totalWithdrawRequestedInTheory = 0; //Now that I think about it, we could probably do something like this to burn immediately and avoid delayed prices altogether. But it is getting too complicated, and the current system helps MASTER holders anyways. if(what > totalStakeRequestedInTheory) //Withdraw > Stake: Only withdraw. We need a bit more to pay our debt. { what = what.sub(totalStakeRequestedInTheory); //Withdraw less to handle "stake". Reserves (staked amount chilling in the contract) will cover some of our debt (requested withdraws). totalStakeRequestedInTheory = 0; //Don't stake in part 2 anymore, as it was already technically "staked" here. } else //Stake >= Withdraw: Only stake or do nothing. We have enough THEORY in our reserves to support all the withdraws. { totalStakeRequestedInTheory = totalStakeRequestedInTheory.sub(what); //Stake less to handle "withdraw". Reserves (staked amount chilling in the contract) will cover all of our debt (requested withdraws). Stake the remaining reserves here, if any. what = 0; //Don't withdraw in part 1 anymore, it was already "withdrawn" here. } if(what > 0) { theoretics.withdraw(what); uint256 newBalanceTheory = theory.balanceOf(address(this)); uint256 whatAfterWithdrawFee = newBalanceTheory.sub(initialBalanceTheory); uint256 withdrawFee = what.sub(whatAfterWithdrawFee); address daoFund = treasury.daoFund(); if(!allowEmergency || withdrawFee > 0 && theory.allowance(daoFund, address(this)) >= withdrawFee) theory.safeTransferFrom(daoFund, address(this), withdrawFee); //Send withdraw fee back to us. Don't allow this function to hold up funds. // if(extraTheoryWithdrawRequested > 0) // { // theory.safeTransfer(treasury.daoFund(), extraTheoryWithdrawRequested); // extraTheoryWithdrawRequested = 0; // } } else { theoretics.claimReward(); //Claim. } } //theoretics.setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs, _pegMaxUnlock); //Unlock uint256 extraLocked = game.lockOf(address(this)).sub(game.canUnlockAmount(address(this))); if(extraLocked > 0) { game.unlockForUser(address(this), extraLocked); } uint256 newBalance = game.totalBalanceOf(address(this)); uint256 amount = newBalance.sub(initialBalance); totalGameUnclaimed = totalGameUnclaimed.add(amount); //Calculate amount to earn // Create & add new snapshot uint256 prevRPS = getLatestSnapshot().rewardPerShare; uint256 supply = totalSupply(); //Nobody earns any GAME if everyone withdraws. If that's the case, all GAME goes to the treasury's daoFund. uint256 nextRPS = supply == 0 ? prevRPS : prevRPS.add(amount.mul(1e18).div(supply)); //Otherwise, GAME is distributed amongst those who have not yet burned their MASTER. if(supply == 0) { game.safeTransfer(treasury.daoFund(), amount); } MasterSnapshot memory newSnapshot = MasterSnapshot({ time: block.number, rewardReceived: amount, rewardPerShare: nextRPS }); masterHistory.push(newSnapshot); lastInitiatePart1Epoch = theoretics.epoch(); lastInitiatePart1Block = block.number; } function _sellToTheory() internal { UserInfo storage user = userInfo[msg.sender]; //require(block.timestamp >= user.lockToTime, "Still locked!"); //Allow locked people to withdraw since it no longer counts towards their rewards. require(user.withdrawRequestedInMaster > 0, "No zero amount allowed."); require(theoretics.getCurrentWithdrawEpochs() == 0 || lastInitiatePart1Block > user.lastWithdrawRequestBlock, "Initiator Part 1 not yet called or called too soon."); //Burn uint256 what = user.withdrawRequestedInTheory; totalWithdrawUnclaimedInTheory = totalWithdrawUnclaimedInTheory.sub(what); //We already handle burn en-masse uint256 amountInMaster = user.withdrawRequestedInMaster; user.withdrawRequestedInMaster = 0; user.withdrawRequestedInTheory = 0; theory.safeTransfer(msg.sender, what); emit Withdraw(msg.sender, amountInMaster, what); } //Public functions function buyFromTheory(uint256 amountInTheory, uint256 lockTime) public onlyOneBlock updateReward(msg.sender) { require(amountInTheory > 0, "No zero amount allowed."); UserInfo storage user = userInfo[msg.sender]; uint256 withdrawEpochs = theoretics.getCurrentWithdrawEpochs(); require(user.withdrawRequestedInMaster == 0 && (withdrawEpochs == 0 || user.lastWithdrawRequestBlock == 0 || lastInitiatePart1Block > user.lastWithdrawRequestBlock), "Cannot stake with a withdraw pending."); //Lock if(lockTime < minLockTime) lockTime = minLockTime; //Just in case we want bonuses/airdrops for those who lock longer. This would have to be done outside of this contract, as it provides no bonuses by itself. uint256 nextTime = block.timestamp.add(lockTime); user.chosenLockTime = lockTime; if(nextTime > user.lockToTime) user.lockToTime = nextTime; //Mint uint256 what = theoryToMaster(amountInTheory); theory.safeTransferFrom(msg.sender, address(this), amountInTheory); _mint(msg.sender, what); //Don't delay mint, since price has to stay the same or higher (or else withdraws could be borked). Delayed buys could make it go lower. if(lastInitiatePart2Epoch == theoretics.epoch() || withdrawEpochs == 0) { address theoreticsAddress = address(theoretics); theory.safeApprove(theoreticsAddress, 0); theory.safeApprove(theoreticsAddress, amountInTheory); theoretics.stake(amountInTheory); //Stake if we already have staked this epoch or are at 0 withdraw epochs. } else { totalStakeRequestedInTheory = totalStakeRequestedInTheory.add(amountInTheory); } user.lastStakeRequestBlock = block.number; emit Deposit(msg.sender, amountInTheory, what); } function requestSellToTheory(uint256 amountInMaster, bool allowEmergency) public onlyOneBlock updateReward(msg.sender) { UserInfo storage user = userInfo[msg.sender]; require(block.timestamp >= user.lockToTime || emergencyUnlock, "Still locked!"); require(amountInMaster > 0, "No zero amount allowed."); uint256 withdrawEpochs = theoretics.getCurrentWithdrawEpochs(); require(withdrawEpochs == 0 || user.lastStakeRequestBlock == 0 || lastInitiatePart2Block > user.lastStakeRequestBlock, "Cannot withdraw with a stake pending."); if(amountInMaster == balanceOf(msg.sender)) _claimGame(); //Final GAME claim before moving to THEORY. //Add. Since we have to transfer here to avoid transfer exploits, we cannot do a replace. _transfer(msg.sender, address(this), amountInMaster); //This will handle exceeded balance. user.withdrawRequestedInMaster = user.withdrawRequestedInMaster.add(amountInMaster); totalWithdrawRequestedInMaster = totalWithdrawRequestedInMaster.add(amountInMaster); //If price increases between now and burn, the extra will be used for future withdrawals, increasing the price further. //Price should not be able to decrease between now and burn. uint256 what = masterToTheory(amountInMaster); user.withdrawRequestedInTheory = user.withdrawRequestedInTheory.add(what); totalWithdrawRequestedInTheory = totalWithdrawRequestedInTheory.add(what); totalWithdrawUnclaimedInTheory = totalWithdrawUnclaimedInTheory.add(what); user.lastWithdrawRequestBlock = block.number; emit WithdrawRequest(msg.sender, amountInMaster, what); if(withdrawEpochs == 0) { _initiatePart1(allowEmergency); _sellToTheory(); } } function sellToTheory() public onlyOneBlock updateReward(msg.sender) { require(theoretics.getCurrentWithdrawEpochs() != 0, "Call requestSellToTheory instead."); _sellToTheory(); } function claimGame() public onlyOneBlock updateReward(msg.sender) { require(earned(msg.sender) > 0, "No GAME to claim."); //Avoid locking yourself for nothing. //If you claim GAME after your lock time is over, you are locked up for 30 more days by default. UserInfo storage user = userInfo[msg.sender]; if(block.timestamp >= user.lockToTime) { user.lockToTime = block.timestamp.add(unlockedClaimPenalty); } _claimGame(); } function initiatePart1(bool allowEmergency) public onlyOneBlock { uint256 withdrawEpochs = theoretics.getCurrentWithdrawEpochs(); uint256 nextEpochPoint = theoretics.nextEpochPoint(); uint256 epoch = theoretics.epoch(); //Every getCurrentWithdrawEpochs() epochs require(withdrawEpochs == 0 || epoch.mod(withdrawEpochs) == 0, "WE"); // Must call at a withdraw epoch. //Only in last 30 minutes of the epoch. require(block.timestamp > nextEpochPoint || nextEpochPoint.sub(block.timestamp) <= 30 minutes, "30"); //Must be called at most 30 minutes before epoch ends. //No calling twice within the epoch. require(lastInitiatePart1Epoch != epoch, "AC"); //Already called. _initiatePart1(allowEmergency); } function initiatePart2() public onlyOneBlock { uint256 withdrawEpochs = theoretics.getCurrentWithdrawEpochs(); uint256 nextEpochPoint = theoretics.nextEpochPoint(); uint256 epoch = theoretics.epoch(); //Every getCurrentWithdrawEpochs() epochs require(withdrawEpochs == 0 || epoch.mod(withdrawEpochs) == 0, "WE"); //Must call at a withdraw epoch. //Only in last 30 minutes of the epoch. require(block.timestamp > nextEpochPoint || nextEpochPoint.sub(block.timestamp) <= 30 minutes, "30"); //Must be called at most 30 minutes before epoch ends. //No calling twice within the epoch. require(lastInitiatePart2Epoch != epoch, "AC"); //Already called. //No calling before part 1. require(lastInitiatePart1Epoch == epoch, "IP1"); //Initiate part 1 first. if(totalStakeRequestedInTheory > 0) { address theoreticsAddress = address(theoretics); theory.safeApprove(theoreticsAddress, 0); theory.safeApprove(theoreticsAddress, totalStakeRequestedInTheory); theoretics.stake(totalStakeRequestedInTheory); //extraTheoryAdded = extraTheoryAdded.add(extraTheoryStakeRequested); //Track extra theory that we have staked. //extraTheoryStakeRequested = 0; totalStakeRequestedInTheory = 0; } lastInitiatePart2Epoch = epoch; lastInitiatePart2Block = block.number; } function approveTransferFrom(address from) public { userInfo[msg.sender].approveTransferFrom = from; } function unlockGame() public { uint256 amount = canUnlockAmountGame(msg.sender); uint256 lockOf = game.lockOf(msg.sender); uint256 gameAmount = game.canUnlockAmount(msg.sender); UserInfo memory user = userInfo[msg.sender]; require(user.gameLocked > 0 || lockOf > gameAmount, "ILT"); //Insufficient locked tokens if (user.gameLocked > 0) _unlockGame(msg.sender, amount); //Unlock GAME in smart contract as well (only if it won't revert), otherwise still have to call unlock() first. if (lockOf > gameAmount) game.unlockForUser(msg.sender, 0); } }
extraTheoryAdded = extraTheoryAdded.add(amount); Track extra theory that we will stake immediately.extraTheoryStakeRequested = extraTheoryStakeRequested.add(amount);
function stakeExternalTheory(uint256 amount) external onlyAuthorized onlyOneBlock { if(lastInitiatePart2Epoch == theoretics.epoch() || theoretics.getCurrentWithdrawEpochs() == 0) { theory.safeApprove(address(theoretics), 0); theory.safeApprove(address(theoretics), amount); } else { totalStakeRequestedInTheory = totalStakeRequestedInTheory.add(amount); } }
13,139,323
./full_match/43113/0xBdb19D9175BEdBBCdCc70cC70cC7e5b9F2EC7bFA/sources/github/lydiafinance/lydia-farm/contracts/MasterChef.sol
Withdraw LP tokens from Croesus.
function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw LYD by unstaking'); 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.accLydPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeLydTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accLydPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
7,151,846
//Address: 0x398acb6594866bc7ac3a23e925b2fc3727c19828 //Contract name: Presale //Balance: 0 Ether //Verification Date: 1/19/2018 //Transacion Count: 1317 // CODE STARTS HERE pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/Discounts.sol library Discounts { using SafeMath for uint256; /************************************************************************** * TYPES *************************************************************************/ /* * Top-level struct for grouping of tiers with a base purchase rate */ struct Collection { Tier[] tiers; // number of tokens per wei uint256 baseRate; } /* * Struct for a given tier - discount and availability */ struct Tier { // discount the set purchase price, expressed in basis points (‱) // range (0‱ .. 10,000‱) corresponds to (0.00% .. 100.00%) uint256 discount; // number of remaining available tokens in tier uint256 available; } // upper-bound of basis point scale uint256 public constant MAX_DISCOUNT = 10000; /************************************************************************** * CREATE *************************************************************************/ /* * @dev Add a new tier at the end of the list * @param _discount - Discount in basis points * @param _available - Available supply at tier */ function addTier( Collection storage self, uint256 _discount, uint256 _available ) internal { self.tiers.push(Tier({ discount: _discount, available: _available })); } /************************************************************************** * PURCHASE *************************************************************************/ /* * @dev Subtracts supply from tiers starting at a minimum, using up funds * @param _amount - Maximum number of tokens to purchase * @param _funds - Allowance in Wei * @param _minimumTier - Minimum tier to start purchasing from * @return Total tokens purchased and remaining funds in wei */ function purchaseTokens( Collection storage self, uint256 _amount, uint256 _funds, uint256 _minimumTier ) internal returns ( uint256 purchased, uint256 remaining ) { uint256 issue = 0; // tracks total tokens to issue remaining = _funds; uint256 available; // var for available tokens at tier uint256 spend; // amount spent at tier uint256 affordable; // var for # funds can pay for at tier uint256 purchase; // var for # to purchase at tier // for each tier starting at minimum // draw from the sent funds and count tokens to issue for (var i = _minimumTier; i < self.tiers.length && issue < _amount; i++) { // get the available tokens left at each tier available = self.tiers[i].available; // compute the maximum tokens that the funds can pay for affordable = _computeTokensPurchasedAtTier(self, i, remaining); // either purchase what the funds can afford, or the whole supply // at the tier if (affordable < available) { purchase = affordable; } else { purchase = available; } // limit the amount purchased up to specified amount // use safemath here in case of unknown overflow risk if (purchase.add(issue) > _amount) { purchase = _amount.sub(issue); } spend = _computeCostForTokensAtTier(self, i, purchase); // decrease available supply at tier self.tiers[i].available -= purchase; // increase tokens to issue issue += purchase; // decrement funds to proceed remaining -= spend; } return (issue, remaining); } /************************************************************************** * PRICE MATH *************************************************************************/ // @return total number of tokens for an amount of wei, discount-adjusted function _computeTokensPurchasedAtTier( Collection storage self, uint256 _tier, uint256 _wei ) private view returns (uint256) { var paidBasis = MAX_DISCOUNT.sub(self.tiers[_tier].discount); return _wei.mul(self.baseRate).mul(MAX_DISCOUNT) / paidBasis; } // @return cost in wei for that many tokens function _computeCostForTokensAtTier( Collection storage self, uint256 _tier, uint256 _tokens ) private view returns (uint256) { var paidBasis = MAX_DISCOUNT.sub(self.tiers[_tier].discount); var numerator = _tokens.mul(paidBasis); var denominator = MAX_DISCOUNT.mul(self.baseRate); var floor = _tokens.mul(paidBasis).div( MAX_DISCOUNT.mul(self.baseRate) ); // must round up cost to next wei (cause token computation rounds down) if (numerator % denominator != 0) { floor = floor + 1; } return floor; } } // File: contracts/Limits.sol library Limits { using SafeMath for uint256; struct PurchaseRecord { uint256 blockNumber; uint256 amount; } struct Window { uint256 amount; // # of tokens uint256 duration; // # of blocks mapping (address => PurchaseRecord) purchases; } /* * Record a purchase towards a purchaser's cap limit * @dev resets the purchaser's cap if the window duration has been met * @param _participant - purchaser * @param _amount - token amount of new purchase */ function recordPurchase( Window storage self, address _participant, uint256 _amount ) internal { var blocksLeft = getBlocksUntilReset(self, _participant); var record = self.purchases[_participant]; if (blocksLeft == 0) { record.amount = _amount; record.blockNumber = block.number; } else { record.amount = record.amount.add(_amount); } } /* * Retrieve the current limit for a given participant, based on previous * purchase history * @param _participant - Purchaser * @return amount of tokens left for participant with cap */ function getLimit(Window storage self, address _participant) public view returns (uint256 _amount) { var blocksLeft = getBlocksUntilReset(self, _participant); if (blocksLeft == 0) { return self.amount; } else { return self.amount.sub(self.purchases[_participant].amount); } } function getBlocksUntilReset(Window storage self, address _participant) public view returns (uint256 _blocks) { var expires = self.purchases[_participant].blockNumber + self.duration; if (block.number > expires) { return 0; } else { return expires - block.number; } } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/SeeToken.sol /** * @title SEE Token * Not a full ERC20 token - prohibits transferring. Serves as a record of * account, to redeem for real tokens after launch. */ contract SeeToken is Claimable { using SafeMath for uint256; string public constant name = "See Presale Token"; string public constant symbol = "SEE"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint256) balances; event Issue(address to, uint256 amount); /** * @dev Issue new tokens * @param _to The address that will receive the minted tokens * @param _amount the amount of new tokens to issue */ function issue(address _to, uint256 _amount) onlyOwner public { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Issue(_to, _amount); } /** * @dev Get the balance for a particular token holder * @param _holder The token holder's address * @return The holder's balance */ function balanceOf(address _holder) public view returns (uint256 balance) { balance = balances[_holder]; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: contracts/Presale.sol contract Presale is Claimable, Pausable { using Discounts for Discounts.Collection; using Limits for Limits.Window; struct Participant { bool authorized; uint256 minimumTier; } /************************************************************************** * STORAGE / EVENTS *************************************************************************/ SeeToken token; Discounts.Collection discounts; Limits.Window cap; mapping (address => Participant) participants; event Tier(uint256 discount, uint256 available); /************************************************************************** * CONSTRUCTOR / LIFECYCLE *************************************************************************/ function Presale(address _token) public { token = SeeToken(_token); paused = true; } /* * @dev (Done as part of migration) Claims ownership of token contract */ function claimToken() public { token.claimOwnership(); } /* * Allow purchase * @dev while paused */ function unpause() onlyOwner whenPaused whenRateSet whenCapped whenOwnsToken public { super.unpause(); } /************************************************************************** * ADMIN INTERFACE *************************************************************************/ /* * Set the base purchase rate for the token * @param _purchaseRate - number of tokens granted per wei */ function setRate(uint256 _purchaseRate) onlyOwner whenPaused public { discounts.baseRate = _purchaseRate; } /* * Specify purchasing limits for a single account: the limit of tokens * that a participant may purchase in a set amount of time (blocks) * @param _amount - Number of tokens * @param _duration - Number of blocks */ function limitPurchasing(uint256 _amount, uint256 _duration) onlyOwner whenPaused public { cap.amount = _amount; cap.duration = _duration; } /* * Add a tier with a given discount and available supply * @param _discount - Discount in basis points * @param _available - Available supply at tier */ function addTier(uint256 _discount, uint256 _available) onlyOwner whenPaused public { discounts.addTier(_discount, _available); Tier(_discount, _available); } /* * Authorize a group of participants for a tier * @param _minimumTier - minimum tier for list of participants * @param _participants - array of authorized addresses */ function authorizeForTier(uint256 _minimumTier, address[] _authorized) onlyOwner public { for (uint256 i = 0; i < _authorized.length; i++) { participants[_authorized[i]] = Participant({ authorized: true, minimumTier: _minimumTier }); } } /* * Withdraw balance from presale */ function withdraw() onlyOwner public { owner.transfer(this.balance); } /************************************************************************** * PURCHASE INTERFACE *************************************************************************/ /* * Fallback (default) function. * @dev Forwards to `purchaseTokens()` */ function () public payable { purchaseTokens(); } /* * Public purchase interface for authorized Dragon Holders * @dev Purchases tokens starting in authorized minimum tier */ function purchaseTokens() onlyAuthorized whenNotPaused public payable { var limit = cap.getLimit(msg.sender); var (purchased, refund) = discounts.purchaseTokens( limit, msg.value, participants[msg.sender].minimumTier ); cap.recordPurchase(msg.sender, purchased); // issue new tokens token.issue(msg.sender, purchased); // if there are funds left, send refund if (refund > 0) { msg.sender.transfer(refund); } } /************************************************************************** * PRICING / AVAILABILITY - VIEW INTERFACE *************************************************************************/ /* * Get terms for purchasing limit window * @return number of tokens and duration in blocks */ function getPurchaseLimit() public view returns (uint256 _amount, uint256 _duration) { _amount = cap.amount; _duration = cap.duration; } /* * Get tiers currently set up, with discounts and available supplies * @return array of tuples (discount, available) */ function getTiers() public view returns (uint256[2][]) { var records = discounts.tiers; uint256[2][] memory tiers = new uint256[2][](records.length); for (uint256 i = 0; i < records.length; i++) { tiers[i][0] = records[i].discount; tiers[i][1] = records[i].available; } return tiers; } /* * Get available supply for each tier for a given participant * @dev starts at minimum tier for participant (requiring auth) * @return available supply by tier index, zeroes for non-auth */ function getAvailability(address _participant) public view returns (uint256[]) { var participant = participants[_participant]; uint256 minimumTier = participant.minimumTier; // minor HACK - if the participant isn't authorized, just set the // minimum tier above the bounds if (!participant.authorized) { minimumTier = discounts.tiers.length; } uint256[] memory tiers = new uint256[](discounts.tiers.length); for (uint256 i = minimumTier; i < tiers.length; i++) { tiers[i] = discounts.tiers[i].available; } return tiers; } /************************************************************************** * MODIFIERS *************************************************************************/ /* * @dev require participant is whitelist-authorized */ modifier onlyAuthorized() { require(participants[msg.sender].authorized); _; } /* * @dev baseRate will default to 0 */ modifier whenRateSet() { require(discounts.baseRate != 0); _; } /* * @dev to prevent accidentally capping at 0 */ modifier whenCapped() { require(cap.amount != 0); _; } /* * @dev asserts zeppelin Claimable workflow is finalized */ modifier whenOwnsToken() { require(token.owner() == address(this)); _; } }
Withdraw balance from presale/
function withdraw() onlyOwner public { owner.transfer(this.balance); }
1,785,704
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Pausable.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "../libs/Strings.sol"; import "../libs/AddressSet.sol"; import "../libs/UInt256Set.sol"; import "../access/Controllable.sol"; import "../interfaces/INFTGemMultiToken.sol"; /** * @dev ProxyContract placeholder - the proxy delegate */ contract OwnableDelegateProxy { } /** * @dev a registry of proxies */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @dev a mock object for testing */ contract MockProxyRegistry { function proxies(address input) external pure returns (address) { return input; } } /** * @dev the primary multitoken contract */ contract NFTGemMultiToken is ERC1155Pausable, ERC1155Holder, INFTGemMultiToken, Controllable { using AddressSet for AddressSet.Set; using UInt256Set for UInt256Set.Set; using Strings for string; // proxy registries for exchanges to enable no-fee trading AddressSet.Set private proxyRegistries; address private registryManager; // total balance per token id mapping(uint256 => uint256) private _totalBalances; // time-locked tokens mapping(address => mapping(uint256 => uint256)) private _tokenLocks; // lists of held tokens by user mapping(address => UInt256Set.Set) private _heldTokens; // list of token holders mapping(uint256 => AddressSet.Set) private _tokenHolders; // token types and token pool addresses, to link the multitoken to the tokens created on it mapping(uint256 => INFTGemMultiToken.TokenType) private _tokenTypes; mapping(uint256 => address) private _tokenPools; /** * @dev Contract initializer. */ constructor() ERC1155("https://metadata.nftgem.host/") { _addController(msg.sender); registryManager = msg.sender; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC1155Receiver) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev timelock the tokens from moving until the given time */ function lock(uint256 token, uint256 timestamp) external override { require(_tokenLocks[_msgSender()][token] < timestamp, "ALREADY_LOCKED"); _tokenLocks[_msgSender()][token] = timestamp; } /** * @dev unlock time for token / id */ function unlockTime(address account, uint256 token) external view override returns (uint256 theTime) { theTime = _tokenLocks[account][token]; } /** * @dev Returns the metadata URI for this token type */ function uri(uint256 _id) public view override(ERC1155) returns (string memory) { // the URI override is here to support IPFS addresses - we need to do the // id concat here because IPFS can't do it. This makes this call take a little // longer but the advantage is that the call returns an already-formed URI require( _totalBalances[_id] != 0, "NFTGemMultiToken#uri: NONEXISTENT_TOKEN" ); return Strings.strConcat( ERC1155Pausable(this).uri(_id), Strings.uint2str(_id) ); } /** * @dev returns an array of held tokens for the token holder */ function heldTokens(address holder) external view override returns (uint256[] memory) { return _heldTokens[holder].keyList; } /** * @dev held token at index for token holder */ function allHeldTokens(address holder, uint256 _idx) external view override returns (uint256) { return _heldTokens[holder].keyList[_idx]; } /** * @dev Returns the count of held tokens for the token holder */ function allHeldTokensLength(address holder) external view override returns (uint256) { return _heldTokens[holder].keyList.length; } /** * @dev Returns an array of token holders for the given token id */ function tokenHolders(uint256 _token) external view override returns (address[] memory) { return _tokenHolders[_token].keyList; } /** * @dev token holder at index for token id */ function allTokenHolders(uint256 _token, uint256 _idx) external view override returns (address) { return _tokenHolders[_token].keyList[_idx]; } /** * @dev Returns the count of token holders for the held token */ function allTokenHoldersLength(uint256 _token) external view override returns (uint256) { return _tokenHolders[_token].keyList.length; } /** * @dev Returns the total balance minted of this type */ function totalBalances(uint256 _id) external view override returns (uint256) { return _totalBalances[_id]; } /** * @dev Returns proxy registry at index */ function allProxyRegistries(uint256 _idx) external view override returns (address) { return proxyRegistries.keyList[_idx]; } /** * @dev Returns the registyry manager account */ function getRegistryManager() external view override returns (address) { return registryManager; } /** * @dev set the registry manager account */ function setRegistryManager(address newManager) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); require(newManager != address(0), "UNAUTHORIZED"); registryManager = newManager; } /** * @dev a count of proxy registries */ function allProxyRegistriesLength() external view override returns (uint256) { return proxyRegistries.keyList.length; } /** * @dev add a proxy registry to the list */ function addProxyRegistry(address registry) external override { require( msg.sender == registryManager || _controllers[msg.sender] == true, "UNAUTHORIZED" ); proxyRegistries.insert(registry); } /** * @dev remove the proxy registry from the list at index */ function removeProxyRegistryAt(uint256 index) external override { require( msg.sender == registryManager || _controllers[msg.sender] == true, "UNAUTHORIZED" ); require(index < proxyRegistries.keyList.length, "INVALID_INDEX"); proxyRegistries.remove(proxyRegistries.keyList[index]); } /** * @dev override base functionality to check proxy registries for approvers */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. for (uint256 i = 0; i < proxyRegistries.keyList.length; i++) { ProxyRegistry proxyRegistry = ProxyRegistry( proxyRegistries.keyList[i] ); try proxyRegistry.proxies(_owner) returns ( OwnableDelegateProxy thePr ) { if (address(thePr) == _operator) { return true; } } catch {} } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev mint some amount of tokens. Only callable by token owner */ function mint( address account, uint256 tokenHash, uint256 amount ) external override onlyController { _mint(account, uint256(tokenHash), amount, "0x0"); } /** * @dev mint some amount of tokens to multiple recipients. Only callable by token owner */ function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts ) external override onlyController { _mintBatch(to, ids, amounts, "0x0"); } /** * @dev burn some amount of tokens of multiple token types of account. Only callable by token owner */ function burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) external override onlyController { _burnBatch(account, ids, amounts); } /** * @dev set the data for this tokenhash. points to a token type (1 = claim, 2 = gem) and token pool address */ function setTokenData( uint256 tokenHash, INFTGemMultiToken.TokenType tokenType, address tokenPool ) external override onlyController { _tokenTypes[tokenHash] = tokenType; _tokenPools[tokenHash] = tokenPool; } /** * @dev get the token data for this token tokenhash */ function getTokenData(uint256 tokenHash) external view override returns (INFTGemMultiToken.TokenType tokenType, address tokenPool) { tokenType = _tokenTypes[tokenHash]; tokenPool = _tokenPools[tokenHash]; } /** * @dev internal mint overridden to manage token holders and held tokens lists */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._mint(account, id, amount, data); } /** * @dev internal minttbatch should account for managing lists */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); } /** * @dev burn some amount of tokens. Only callable by token owner */ function burn( address account, uint256 tokenHash, uint256 amount ) external override onlyController { _burn(account, uint256(tokenHash), amount); } /** * @dev internal burn overridden to track lists */ function _burn( address account, uint256 id, uint256 amount ) internal virtual override { super._burn(account, id, amount); } /** * @dev internal burnBatch should account for managing lists */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); } /** * @dev we override this method in order to manager the token holder and held token lists */ 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); for (uint256 i = 0; i < ids.length; i++) { // prevent send if tokens are locked if (from != address(0)) { require( _tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED" ); } // if this is not a mint then remove the held token id from lists if // this is the last token if this type the sender owns if (from != address(0) && balanceOf(from, ids[i]) == amounts[i]) { // find and delete the token id from the token holders held tokens _heldTokens[from].remove(ids[i]); _tokenHolders[ids[i]].remove(from); } // if this is not a burn and receiver does not yet own token then // add that account to the token for that id if (to != address(0) && balanceOf(to, ids[i]) == 0) { // insert the token id from the token holders held tokens\ _heldTokens[to].insert(ids[i]); _tokenHolders[ids[i]].insert(to); } // inc and dec balances for each token type if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])] + (amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])] - (amounts[i]); } } } }
internal burnBatch should account for managing lists/
function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); }
12,955,933
// SPDX-License-Identifier: MIT pragma solidity >= 0.8.0 < 0.9.0; contract Auction { address payable public beneficiary; address public prize; address public highest_bidder; uint public highest_bid; uint private end_time; mapping(address => uint) pendingClaims; event NewHighestBid(address highest_bidder, uint highest_bid); event Ended(address winner, uint amount); receive() external payable { revert("revert from recieve"); } fallback() external payable { revert("revert from fallback"); } modifier OnlyBeneficiary() { require(msg.sender == beneficiary, "Only benefitiary can call this function"); _; } modifier OnlyHighestBidder() { require(msg.sender == highest_bidder, "Only the highest bidder can call this function"); _; } modifier AfterAuctionEnd() { require(block.timestamp > end_time, "This function can only be called after auction ends"); _; } modifier BeforeAuctionEnd() { require(block.timestamp <= end_time, "This function can only be called before the auction ends"); _; } constructor(uint min, address _prize) { beneficiary = payable(msg.sender); end_time = block.timestamp + (min * 60 seconds); prize = _prize; // IPrize(prize).changeOwner(address(this)); } function bid() public payable BeforeAuctionEnd { require(msg.value > highest_bid, "The bid is not higher than the current highest bid"); pendingClaims[highest_bidder] += highest_bid; // set new highest bidder highest_bidder = msg.sender; highest_bid = msg.value; emit NewHighestBid(msg.sender, msg.value); } function claimHighestBid() public OnlyBeneficiary AfterAuctionEnd { beneficiary.transfer(highest_bid); emit Ended(highest_bidder, highest_bid); } function claimPrize() public OnlyHighestBidder AfterAuctionEnd { IPrize(prize).changeOwner(highest_bidder); } function refundBid() public { require(pendingClaims[msg.sender] > 0, "Your claimable amount is 0"); uint ammountToRefund = pendingClaims[msg.sender]; pendingClaims[msg.sender] = 0; payable(msg.sender).transfer(ammountToRefund); } function isEnded() public view returns (bool) { return block.timestamp > end_time; } function getBalance() public view returns (uint){ return address(this).balance; } } interface IPrize { function getOwner() external view returns (address); function changeOwner(address new_owner) external; } contract Prize { address owner; address approved_address; constructor() { owner = msg.sender; } function getOwner() public view returns (address) { return owner; } function changeOwner(address new_owner) public { //require(msg.sender == owner || msg.sender == approved_address, "Unauthorized Address"); owner = new_owner; } function approve(address _approved_address) public { approved_address = _approved_address; } }
require(msg.sender == owner || msg.sender == approved_address, "Unauthorized Address");
function changeOwner(address new_owner) public { owner = new_owner; }
12,556,545
// File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/proxy/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // File: contracts/interfaces/IEmiVesting.sol pragma solidity ^0.6.2; /************************************************************************* * EmiVesting inerface * ************************************************************************/ interface IEmiVesting { function balanceOf(address beneficiary) external view returns (uint256); function getCrowdsaleLimit() external view returns (uint256); } // File: contracts/interfaces/IEmiList.sol pragma solidity ^0.6.2; /************************************************************************* * EmiList inerface * ************************************************************************/ interface IEmiList { function approveTransfer(address from, address to, uint256 amount) external view returns (bool); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: contracts/libraries/Priviledgeable.sol pragma solidity ^0.6.2; abstract contract Priviledgeable { using SafeMath for uint256; using SafeMath for uint256; event PriviledgeGranted(address indexed admin); event PriviledgeRevoked(address indexed admin); modifier onlyAdmin() { require( _priviledgeTable[msg.sender], "Priviledgeable: caller is not the owner" ); _; } mapping(address => bool) private _priviledgeTable; constructor() internal { _priviledgeTable[msg.sender] = true; } function addAdmin(address _admin) external onlyAdmin returns (bool) { require(_admin != address(0), "Admin address cannot be 0"); return _addAdmin(_admin); } function removeAdmin(address _admin) external onlyAdmin returns (bool) { require(_admin != address(0), "Admin address cannot be 0"); _priviledgeTable[_admin] = false; emit PriviledgeRevoked(_admin); return true; } function isAdmin(address _who) external view returns (bool) { return _priviledgeTable[_who]; } //----------- // internals //----------- function _addAdmin(address _admin) internal returns (bool) { _priviledgeTable[_admin] = true; emit PriviledgeGranted(_admin); } } // File: @openzeppelin/contracts/utils/Context.sol 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; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity >=0.6.0 <0.8.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: contracts/libraries/ProxiedERC20.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 ProxiedERC20 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; uint8 private _intialized; /** * @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. */ function _initialize( string memory name, string memory symbol, uint8 decimals ) internal { require(_intialized == 0, "Already intialize"); _name = name; _symbol = symbol; _decimals = decimals; _intialized = 1; } /** * @dev Returns the name of the token. */ function _updateTokenName(string memory newName, string memory newSymbol) internal { _name = newName; _symbol = newSymbol; } /** * @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 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 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 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/libraries/OracleSign.sol pragma solidity ^0.6.2; abstract contract OracleSign { function _splitSignature(bytes memory sig) internal pure returns ( uint8, bytes32, bytes32 ) { require(sig.length == 65, "Incorrect signature length"); bytes32 r; bytes32 s; uint8 v; assembly { //first 32 bytes, after the length prefix r := mload(add(sig, 0x20)) //next 32 bytes s := mload(add(sig, 0x40)) //final byte, first of next 32 bytes v := byte(0, mload(add(sig, 0x60))) } return (v, r, s); } function _recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = _splitSignature(sig); return ecrecover(message, v, r, s); } function _prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } } pragma solidity ^0.6.0; // Exempt from the original UniswapV2Library. library UniswapV2Library { // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(bytes32 initCodeHash, address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), initCodeHash // init code hash )))); } } pragma solidity ^0.6.0; /// @notice based on https://github.com/Uniswap/uniswap-v3-periphery/blob/v1.0.0/contracts/libraries/PoolAddress.sol /// @notice changed compiler version and lib name. /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library UniswapV3Library { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } pragma solidity ^0.6.0; interface IPLPS { function LiquidityProtection_beforeTokenTransfer( address _pool, address _from, address _to, uint _amount) external; function isBlocked(address _pool, address _who) external view returns(bool); function unblock(address _pool, address _who) external; } pragma solidity ^0.6.0; abstract contract UsingLiquidityProtectionService { bool private protected = true; uint64 internal constant HUNDRED_PERCENT = 1e18; bytes32 internal constant UNISWAP = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f; bytes32 internal constant PANCAKESWAP = 0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5; enum UniswapVersion { V2, V3 } enum UniswapV3Fees { _005, // 0.05% _03, // 0.3% _1 // 1% } modifier onlyProtectionAdmin() { protectionAdminCheck(); _; } function token_transfer(address from, address to, uint amount) internal virtual; function token_balanceOf(address holder) internal view virtual returns(uint); function protectionAdminCheck() internal view virtual; function liquidityProtectionService() internal pure virtual returns(address); function uniswapVariety() internal pure virtual returns(bytes32); function uniswapVersion() internal pure virtual returns(UniswapVersion); function uniswapFactory() internal pure virtual returns(address); function counterToken() internal pure virtual returns(address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH } function uniswapV3Fee() internal pure virtual returns(UniswapV3Fees) { return UniswapV3Fees._03; } function protectionChecker() internal view virtual returns(bool) { return ProtectionSwitch_manual(); } function lps() private pure returns(IPLPS) { return IPLPS(liquidityProtectionService()); } function LiquidityProtection_beforeTokenTransfer(address _from, address _to, uint _amount) internal virtual { if (protectionChecker()) { if (!protected) { return; } lps().LiquidityProtection_beforeTokenTransfer(getLiquidityPool(), _from, _to, _amount); } } function revokeBlocked(address[] calldata _holders, address _revokeTo) external onlyProtectionAdmin() { require(protectionChecker(), 'UsingLiquidityProtectionService: protection removed'); protected = false; address pool = getLiquidityPool(); for (uint i = 0; i < _holders.length; i++) { address holder = _holders[i]; if (lps().isBlocked(pool, holder)) { token_transfer(holder, _revokeTo, token_balanceOf(holder)); } } protected = true; } function LiquidityProtection_unblock(address[] calldata _holders) external onlyProtectionAdmin() { require(protectionChecker(), 'UsingLiquidityProtectionService: protection removed'); address pool = getLiquidityPool(); for (uint i = 0; i < _holders.length; i++) { lps().unblock(pool, _holders[i]); } } function disableProtection() external onlyProtectionAdmin() { protected = false; } function isProtected() public view returns(bool) { return protected; } function ProtectionSwitch_manual() internal view returns(bool) { return protected; } function ProtectionSwitch_timestamp(uint _timestamp) internal view returns(bool) { return not(passed(_timestamp)); } function ProtectionSwitch_block(uint _block) internal view returns(bool) { return not(blockPassed(_block)); } function blockPassed(uint _block) internal view returns(bool) { return _block < block.number; } function passed(uint _timestamp) internal view returns(bool) { return _timestamp < block.timestamp; } function not(bool _condition) internal pure returns(bool) { return !_condition; } function feeToUint24(UniswapV3Fees _fee) internal pure returns(uint24) { if (_fee == UniswapV3Fees._03) return 3000; if (_fee == UniswapV3Fees._005) return 500; return 10000; } function getLiquidityPool() public view returns(address) { if (uniswapVersion() == UniswapVersion.V2) { return UniswapV2Library.pairFor(uniswapVariety(), uniswapFactory(), address(this), counterToken()); } require(uniswapVariety() == UNISWAP, 'LiquidityProtection: uniswapVariety() can only be UNISWAP for V3.'); return UniswapV3Library.computeAddress(uniswapFactory(), UniswapV3Library.getPoolKey(address(this), counterToken(), feeToUint24(uniswapV3Fee()))); } } // File: contracts/ESW.sol pragma solidity ^0.6.2; contract ESW is ProxiedERC20, Initializable, Priviledgeable, OracleSign, UsingLiquidityProtectionService { address public dividendToken; address public vesting; uint256 internal _initialSupply; mapping(address => uint256) internal _mintLimit; mapping(address => bool) internal _mintGranted; // <-- been used in previouse implementation, now just reserved at proxy storage // !!!In updates to contracts set new variables strictly below this line!!! //----------------------------------------------------------------------------------- string public codeVersion = "ESW v1.1-145-gf234c9e"; uint256 public constant MAXIMUM_SUPPLY = 200_000_000e18; bool public isFirstMinter = true; address public constant firstMinter = 0xdeb5A983AdC9b25b8A96ae43a65953Ded3939de6; // set to Oracle address public constant secondMinter = 0x9Cf73e538acC5B2ea51396eA1a6DE505f6a68f2b; //set to EmiVesting uint256 public minterChangeBlock; event MinterSwitch(address newMinter, uint256 afterBlock); mapping(address => uint256) public walletNonce; address private _emiList; function initialize() public virtual initializer { _initialize("EmiDAO Token", "ESW", 18); _addAdmin(msg.sender); } /*********************** admin functions *****************************/ function updateTokenName(string memory newName, string memory newSymbol) public onlyAdmin { _updateTokenName(newName, newSymbol); } /** * switchMinter - function for switching between two registered minters * @param isSetFirst - true - set first / false - set second minter */ function switchMinter(bool isSetFirst) public onlyAdmin { isFirstMinter = isSetFirst; minterChangeBlock = block.number + 6646; // 6646 ~24 hours emit MinterSwitch( (isSetFirst ? firstMinter : secondMinter), minterChangeBlock ); } /** * set mint limit for exact contract wallets * @param account - wallet to set mint limit * @param amount - mint limit value */ function setMintLimit(address account, uint256 amount) public onlyAdmin { _mintLimit[account] = amount; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { super.transfer(recipient, amount); return true; } function setListAddress(address emiList) public onlyAdmin { _emiList = emiList; // can be NULL also to remove emiList functionality totally } /*********************** public functions *****************************/ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { super.transferFrom(sender, recipient, amount); return true; } function burn(uint256 amount) public { super._burn(msg.sender, amount); } function burnFromVesting(uint256 amount) external { require(msg.sender == vesting, "Only vesting!"); burn(amount); } /** * mintSigned - oracle signed function allow user to mint ESW tokens * @param recipient - user's wallet for receiving tokens * @param amount - amount to mint * @param nonce - user's mint request number, for security purpose * @param sig - oracle signature, oracle allowance for user to mint tokens */ function mintSigned( address recipient, uint256 amount, uint256 nonce, bytes memory sig ) public { require(recipient == msg.sender, "ESW:sender"); // check sign bytes32 message = _prefixed( keccak256(abi.encodePacked(recipient, amount, nonce, this)) ); require( _recoverSigner(message, sig) == getOracle() && walletNonce[msg.sender] < nonce, "ESW:sign" ); walletNonce[msg.sender] = nonce; _mintAllowed(getOracle(), recipient, amount); } /*********************** view functions *****************************/ function initialSupply() public view returns (uint256) { return _initialSupply; } function balanceOf(address account) public view override returns (uint256) { return super.balanceOf(account); } /** * getMintLimit - read mint limit for wallets * @param account - wallet address * @return - mintlimit for requested wallet */ function getMintLimit(address account) public view returns (uint256) { return _mintLimit[account]; } function getWalletNonce() public view returns (uint256) { return walletNonce[msg.sender]; } /** *first minter address after minterChangeBlock, second before minterChangeBlock *second minter address after minterChangeBlock, first before minterChangeBlock */ function getOracle() public view returns (address) { return ( ( isFirstMinter ? ( block.number >= minterChangeBlock ? firstMinter : secondMinter ) : ( block.number >= minterChangeBlock ? secondMinter : firstMinter ) ) ); } function token_transfer(address _from, address _to, uint _amount) internal override { _transfer(_from, _to, _amount); // Expose low-level token transfer function. } function token_balanceOf(address _holder) internal view override returns(uint) { return balanceOf(_holder); // Expose balance check function. } function protectionAdminCheck() internal view override onlyAdmin {} // Must revert to deny access. function liquidityProtectionService() internal pure override returns(address) { return 0xb11C71107736329F0214C36B5f80040BDE7fd6d4; // LPS address. } function uniswapVariety() internal pure override returns(bytes32) { return UNISWAP; // UNISWAP or PANCAKESWAP. } function uniswapVersion() internal pure override returns(UniswapVersion) { return UniswapVersion.V2; // V2 or V3. } function uniswapFactory() internal pure override returns(address) { return 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; // Replace with the correct address. } function _beforeTokenTransfer(address _from, address _to, uint _amount) internal override { super._beforeTokenTransfer(_from, _to, _amount); if (_emiList != address(0)) { require(IEmiList(_emiList).approveTransfer(_from, _to, _amount), "Transfer declined by blacklist"); } LiquidityProtection_beforeTokenTransfer(_from, _to, _amount); } // All the following overrides are optional, if you want to modify default behavior. // How the protection gets disabled. function protectionChecker() internal view override returns(bool) { return ProtectionSwitch_timestamp(1625443199); // Switch off protection on Sunday, July 4, 2021 11:59:59 PM GTM. // return ProtectionSwitch_block(13000000); // Switch off protection on block 13000000. // return ProtectionSwitch_manual(); // Switch off protection by calling disableProtection(); from owner. Default. } // This token will be pooled in pair with: function counterToken() internal pure override returns(address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH } /*********************** internal functions *****************************/ function _mintAllowed( address allowedMinter, address recipient, uint256 amount ) internal { require( totalSupply().add(amount) <= MAXIMUM_SUPPLY, "ESW:supply_exceeded" ); _mintLimit[allowedMinter] = _mintLimit[allowedMinter].sub(amount); super._mint(recipient, amount); } }
Must revert to deny access.
function protectionAdminCheck() internal view override onlyAdmin {}
518,685
pragma solidity 0.4.24; import "./Ownable.sol"; import "./HelperFunctions.sol"; //@Dev contract responsible for storing raw materials contract RawMaterial is Ownable ,HelperFunctions { struct RawMaterials { address owner; string nameofMaterial; string datePurchased; uint256 DataCount; uint256 DataAccessIndex; bool Activated;//@Dev Indicates whether the RawMaterial is active or not mapping(uint256 =>RawMaterialData) Owned; } //@Dev represents Raw material data struct RawMaterialData { string nameofMaterial; string DateBought; uint256 index; } //@Dev stores raw material data mapping(address => RawMaterials) RawMaterialsData; //@Dev constructor constructor() public { } //@Dev stores raw materials belonging to a specific farmer function storeValue(string name,string datePurchased) public onlyOwner returns (string message) { if(msg.sender==address(0)) { message="Invalid Grower address"; emit GeneralLogger(message); return message; } if(isStringNullorEmpty(name)||isStringNullorEmpty(datePurchased)) { message="Invalid raw material data"; emit GeneralLogger(message); return message; } if(RawMaterialsData[msg.sender].Activated) { RawMaterialsData[msg.sender].Owned[RawMaterialsData[msg.sender].DataCount]=RawMaterialData(name,datePurchased,RawMaterialsData[msg.sender].DataCount); RawMaterialsData[msg.sender].DataCount++; } else { RawMaterialsData[msg.sender]=RawMaterials(msg.sender,name,datePurchased,0,0,true); RawMaterialsData[msg.sender].Owned[RawMaterialsData[msg.sender].DataCount]=RawMaterialData(name,datePurchased,RawMaterialsData[msg.sender].DataCount); RawMaterialsData[msg.sender].DataCount++; } message="Successfully stored Raw Materials Data"; emit GeneralLogger(message); return message; } //@Dev get raw Material function GetRawMaterial() public returns (string name,string datePurchased,bool found ) { if(msg.sender== address(0)) { emit GeneralLogger("Invalid address of owner of raw material"); return (name,datePurchased,false); } if(!RawMaterialsData[msg.sender].Activated) { emit GeneralLogger("No raw materials for owner exist"); return (name,datePurchased,false); } if(RawMaterialsData[msg.sender].DataCount==0) { name=RawMaterialsData[msg.sender].nameofMaterial; datePurchased=RawMaterialsData[msg.sender].datePurchased; found=true; emit GeneralLogger("Found Raw Material Data"); return (name,datePurchased,found); } if(RawMaterialsData[msg.sender].DataAccessIndex >RawMaterialsData[msg.sender].DataCount) { RawMaterialsData[msg.sender].DataAccessIndex=0; emit GeneralLogger("No More resources to return"); return (name,datePurchased,found); } name=RawMaterialsData[msg.sender].Owned[RawMaterialsData[msg.sender].DataAccessIndex].nameofMaterial; datePurchased=RawMaterialsData[msg.sender].Owned[RawMaterialsData[msg.sender].DataAccessIndex].DateBought; found=true; emit GeneralLogger("Found Raw Material"); RawMaterialsData[msg.sender].DataAccessIndex++; return (name,datePurchased,found); } }
@Dev get raw Material
function GetRawMaterial() public returns (string name,string datePurchased,bool found ) { if(msg.sender== address(0)) { emit GeneralLogger("Invalid address of owner of raw material"); return (name,datePurchased,false); } if(!RawMaterialsData[msg.sender].Activated) { emit GeneralLogger("No raw materials for owner exist"); return (name,datePurchased,false); } if(RawMaterialsData[msg.sender].DataCount==0) { name=RawMaterialsData[msg.sender].nameofMaterial; datePurchased=RawMaterialsData[msg.sender].datePurchased; found=true; emit GeneralLogger("Found Raw Material Data"); return (name,datePurchased,found); } if(RawMaterialsData[msg.sender].DataAccessIndex >RawMaterialsData[msg.sender].DataCount) { RawMaterialsData[msg.sender].DataAccessIndex=0; emit GeneralLogger("No More resources to return"); return (name,datePurchased,found); } name=RawMaterialsData[msg.sender].Owned[RawMaterialsData[msg.sender].DataAccessIndex].nameofMaterial; datePurchased=RawMaterialsData[msg.sender].Owned[RawMaterialsData[msg.sender].DataAccessIndex].DateBought; found=true; emit GeneralLogger("Found Raw Material"); RawMaterialsData[msg.sender].DataAccessIndex++; return (name,datePurchased,found); }
12,616,392
./full_match/1/0x799631f24E54d6483A8f820a0C06226fD122086E/sources/inu.sol
SPDX-License-Identifier: Unlicensed
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); pragma solidity ^0.6.12; }
9,818,722
./partial_match/1/0x7837d182a80d9eec653cd39ab63454e819BEE55B/sources/EthericeStaking.sol
set the max staking days _amount the number of days/
function updateMaxStakeDays(uint256 _amount) external onlyOwner { require((_amount <= 300 && _amount > 30), "New value must be <= 300 and > 30"); maxStakeDays = _amount; }
11,004,342
./full_match/11297108099/0xFF9c578cdd0cf53F26bEE8350DB749aE7C2404cC/sources/project_/contracts/GeerProducts.sol
Returns product associated with given productId
function getProductType(string memory productId) public view returns (Product memory) { Product memory product = products[productId]; require( bytes(products[productId].id).length > 0, "Given product ID does not exist" ); return product; }
3,224,278
pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../access/roles/AdministratorRole.sol"; import "../utils/Addresses.sol"; import "../utils/Channels.sol"; import "../utils/Strings.sol"; import "./IVASP.sol"; import "./IVaspManager.sol"; contract VASP is Initializable, Context, Ownable, AdministratorRole, IVASP, IVaspManager { using Addresses for Addresses.AddressSet; using Addresses for address; using Channels for Channels.ChannelSet; using Strings for string; Channels.ChannelSet private _channels; string private _email; string private _handshakeKey; Addresses.AddressSet private _identityClaims; string private _name; string private _postalAddressStreetName; string private _postalAddressBuildingNumber; string private _postalAddressAddressLine; string private _postalAddressPostCode; string private _postalAddressTown; string private _postalAddressCountry; string private _signingKey; Addresses.AddressSet private _trustedPeers; string private _website; /* * @dev Initializes new instance of a smart contract. Should be called after smart contract deployment. * * Can be called only once. * * * @param owner Owner of the smart contract. * * Requirements: * - Should not be the zero address. * * * @param initialAdministrators Initial list of Administrators accounts. * * Requirements: * - Should be a list of unique values. * - Should not contain the zero address. * */ function initialize( address owner ) public initializer { Ownable.initialize(owner); AdministratorRole.initialize(owner); } /* * @dev Assigns the Administrator role to the specified account. * * Can be called only by the Owner. * * * @param account An account to assign the Administrator role to. * * Requirements: * - Should not be the zero address. * - Should not has the Administrator role. * */ function addAdministrator( address account ) public onlyOwner { _addAdministrator(account); } /* * @dev Adds the specified channel to the list of communication channels the VASP accepting for messages. * * Can be called only by an account with the Administrator role. * * @param channel Channel type to add to the channels list. * * Requirements: * - Should not be presented in the channels list. * */ function addChannel( uint8 channel ) external onlyAdministrator { _addChannel(channel); } /* * @dev Adds the specified address to the list of identity claims. * * Can be called only by an account with the Administrator role. * * @param identityClaim Address of the identity claim to add to the identity claims list. * * Requirements: * - Should not be the zero address. * - Should not be presented in the identity claims list. * */ function addIdentityClaim( address identityClaim ) external onlyAdministrator { _addIdentityClaim(identityClaim); } /* * @dev Adds the specified address to the list of trusted peers. * * Can be called only by an account with the Administrator role. * * @param trustedPeer Address of the trusted peer to add to the trusted peers list. * * Requirements: * - Should not be the zero address. * - Should not be presented in the trusted peers list. * */ function addTrustedPeer( address trustedPeer ) external onlyAdministrator { _addTrustedPeer(trustedPeer); } /* * @dev Revokes the Administrator role from the specified account. * * Can be called only by the Owner. * * * @param account An account to revoke the Administrator role from. * * Requirements: * - Should not be the zero address. * - Should not has the Administrator role. * */ function removeAdministrator( address account ) public onlyOwner { _removeAdministrator(account); } /* * @dev Removes the specified channel from the list of communication channels the VASP accepting for messages. * * Can be called only by an account with the Administrator role. * * @param channel Channel type to remove from the channels list. * * Requirements: * - Should be presented in the channels list. * */ function removeChannel( uint8 channel ) external onlyAdministrator { _removeChannel(channel); } /* * @dev Removes the specified address from the list of identity claims. * * Can be called only by an account with the Administrator role. * * @param identityClaim Address of the identity claim to remove from the identity claims list. * * Requirements: * - Should not be the zero address. * - Should be presented in the identity claims list. * */ function removeIdentityClaim( address identityClaim ) external onlyAdministrator { _removeIdentityClaim(identityClaim); } /* * @dev Removes the specified address from the list of trusted peers. * * Can be called only by an account with the Administrator role. * * @param trustedPeer Address of the trusted peer to remove from the trusted peers list. * * Requirements: * - Should not be the zero address. * - Should be presented in the trusted peers list. * */ function removeTrustedPeer( address trustedPeer ) external onlyAdministrator { _removeTrustedPeer(trustedPeer); } /* * @dev Sets the e-mail address of the VASP. * * * @param email New e-mail address value * * Requirements: * - Should not be an empty string. * - Should not be equal to the current e-mail. * */ function setEmail( string calldata email ) external onlyAdministrator { _setEmail(email); } /* * @dev Sets the handshake key. * * * @param handshakeKey New handshake key value * * Requirements: * - Should not be an empty string. * - Should not be equal to the current handshake key. * */ function setHandshakeKey( string calldata handshakeKey ) external onlyAdministrator { _setHandshakeKey(handshakeKey); } /* * @dev Sets the VASP legal name. * * * @param name New name value * * Requirements: * - Should not be an empty string. * - Should not be equal to the current name. * */ function setName( string calldata name ) external onlyAdministrator { _setName(name); } /* * @dev Sets the VASP postal address. */ function setPostalAddress( string calldata streetName, string calldata buildingNumber, string calldata postCode, string calldata town, string calldata country ) external onlyAdministrator { require(!streetName.isEmpty(), "VASP: street name is not specified"); require(!buildingNumber.isEmpty(), "VASP: building number is not specified"); _setPostalAddress(streetName, buildingNumber, /* addressLine */ "", postCode, town, country); } /* * @dev Sets the VASP postal address. */ function setPostalAddressLine( string calldata addressLine, string calldata postCode, string calldata town, string calldata country ) external onlyAdministrator { require(!addressLine.isEmpty(), "VASP: address line is not specified"); _setPostalAddress(/* streetName */ "", /* buildingNumber */ "", addressLine, postCode, town, country); } /* * @dev Sets the signing key. * * * @param signingKey New signing key value * * Requirements: * - Should not be an empty string. * - Should not be equal to the current signing key. * */ function setSigningKey( string calldata signingKey ) external onlyAdministrator { _setSigningKey(signingKey); } /** * @dev Sets the url of the website of the VASP. * * * @param website New website url * * Requirements: * - Should not be an empty string. * - Should not be equal to the current website url. * */ function setWebsite( string calldata website ) external onlyAdministrator { _setWebsite(website); } /** * @dev See {IVASP-channels}. */ function channels( uint256 skip, uint256 take ) external view returns (uint8[] memory) { return _channels.toArray(skip, take); } /** * @dev See {IVASP-channelsCount}. */ function channelsCount() external view returns (uint256) { return _channels.count(); } /** * @dev See {IVASP-code}. */ function code() external view returns (bytes4) { bytes memory addressBytes = abi.encodePacked(address(this)); bytes4 result; bytes4 x = bytes4(0xff000000); result ^= (x & addressBytes[16]) >> 0; result ^= (x & addressBytes[17]) >> 8; result ^= (x & addressBytes[18]) >> 16; result ^= (x & addressBytes[19]) >> 24; return result; } /** * @dev See {IVASP-email}. */ function email() external view returns (string memory) { return _email; } /** * @dev See {IVASP-handshakeKey}. */ function handshakeKey() external view returns (string memory) { return _handshakeKey; } /** * @dev See {IVASP-identityClaims}. */ function identityClaims( uint256 skip, uint256 take ) external view returns (address[] memory) { return _identityClaims.toArray(skip, take); } /** * @dev See {IVASP-identityClaimsCount}. */ function identityClaimsCount() external view returns (uint256) { return _identityClaims.count(); } /** * @dev See {IVASP-name}. */ function name() external view returns (string memory) { return _name; } /** * @dev See {IVASP-postalAddress}. */ function postalAddress() external view returns ( string memory streetName, string memory buildingNumber, string memory addressLine, string memory postCode, string memory town, string memory country ) { streetName = _postalAddressStreetName; buildingNumber = _postalAddressBuildingNumber; addressLine = _postalAddressAddressLine; postCode = _postalAddressPostCode; town = _postalAddressTown; country = _postalAddressCountry; } /** * @dev See {IVASP-signingKey}. */ function signingKey() external view returns (string memory) { return _signingKey; } /** * @dev See {IVASP-trustedPeers}. */ function trustedPeers( uint256 skip, uint256 take ) external view returns (address[] memory) { return _trustedPeers.toArray(skip, take); } /** * @dev See {IVASP-trustedPeersCount}. */ function trustedPeersCount() external view returns (uint256) { return _trustedPeers.count(); } /** * @dev See {IVASP-website}. */ function website() external view returns (string memory) { return _website; } function _addChannel( uint8 channel ) private { _channels.add(channel); emit ChannelAdded(channel); } function _addIdentityClaim( address identityClaim ) private { require(!identityClaim.isZeroAddress(), "VASP: identity claim is the zero address"); _identityClaims.add(identityClaim); emit IdentityClaimAdded(identityClaim); } function _addTrustedPeer( address trustedPeer ) private { require(!trustedPeer.isZeroAddress(), "VASP: trusted peer is the zero address"); _trustedPeers.add(trustedPeer); emit TrustedPeerAdded(trustedPeer); } function _removeChannel( uint8 channel ) private { _channels.remove(channel); emit ChannelRemoved(channel); } function _removeIdentityClaim( address identityClaim ) private { require(!identityClaim.isZeroAddress(), "VASP: identity claim is the zero address"); _identityClaims.remove(identityClaim); emit IdentityClaimRemoved(identityClaim); } function _removeTrustedPeer( address trustedPeer ) private { require(!trustedPeer.isZeroAddress(), "VASP: trusted peer is the zero address"); _trustedPeers.remove(trustedPeer); emit TrustedPeerRemoved(trustedPeer); } function _setEmail( string memory newEmail ) private { require(!newEmail.isEmpty(), "VASP: newEmail is an empty string"); require(!newEmail.equals(_email), "VASP: specified e-mail has already been set"); _email = newEmail; emit EmailChanged(newEmail); } function _setHandshakeKey( string memory newHandshakeKey ) private { require(!newHandshakeKey.isEmpty(), "VASP: newHandshakeKey is an empty string"); require(!newHandshakeKey.equals(_handshakeKey), "VASP: specified handshake key has already been set"); _handshakeKey = newHandshakeKey; emit HandshakeKeyChanged(newHandshakeKey); } function _setName( string memory newName ) private { require(!newName.isEmpty(), "VASP: newName is an empty string"); require(!newName.equals(_name), "VASP: specified name has already been set"); _name = newName; emit NameChanged(newName); } function _setSigningKey( string memory newSigningKey ) private { require(!newSigningKey.isEmpty(), "VASP: newSigningKey is an empty string"); require(!newSigningKey.equals(_signingKey), "VASP: specified signing key has already been set"); _signingKey = newSigningKey; emit SigningKeyChanged(newSigningKey); } function _setPostalAddress( string memory streetName, string memory buildingNumber, string memory addressLine, string memory postCode, string memory town, string memory country ) private { require(!postCode.isEmpty(), "VASP: post code is not specified"); require(!town.isEmpty(), "VASP: town is not specified"); require(!country.isEmpty(), "VASP: country is not specified"); bool postalAddressChanged = !streetName.equals(_postalAddressStreetName) || !buildingNumber.equals(_postalAddressBuildingNumber) || !addressLine.equals(_postalAddressAddressLine) || !postCode.equals(_postalAddressPostCode) || !town.equals(_postalAddressTown) || !country.equals(_postalAddressCountry); require(postalAddressChanged, "VASP: specified postal address has already been set"); _postalAddressStreetName = streetName; _postalAddressBuildingNumber = buildingNumber; _postalAddressAddressLine = addressLine; _postalAddressPostCode = postCode; _postalAddressTown = town; _postalAddressCountry = country; emit PostalAddressChanged(streetName, buildingNumber, addressLine, postCode, town, country); } function _setWebsite( string memory newWebsite ) private { require(!newWebsite.isEmpty(), "VASP: newWebsite is an empty string"); require(!newWebsite.equals(_website), "VASP: specified website has already been set"); _website = newWebsite; emit WebsiteChanged(newWebsite); } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
See {IVASP-handshakeKey}./
function handshakeKey() external view returns (string memory) { return _handshakeKey; }
13,101,942
pragma solidity ^0.4.13; /* Proxy Buyer ======================== */ // ERC20 Interface: https://github.com/ethereum/EIPs/issues/20 contract ERC20 { function transfer(address _to, uint256 _value) returns (bool success); function balanceOf(address _owner) constant returns (uint256 balance); } contract ICOBuyer { // Emergency kill switch in case a critical bug is found. address public developer = 0xF23B127Ff5a6a8b60CC4cbF937e5683315894DDA; // The crowdsale address. Settable by the developer. address public sale; // The token address. Settable by the developer. ERC20 public token; // Allows the developer to set the crowdsale and token addresses. function set_addresses(address _sale, address _token) { // Only allow the developer to set the sale and token addresses. require(msg.sender == developer); // Only allow setting the addresses once. // Set the crowdsale and token addresses. sale = _sale; token = ERC20(_token); } // Withdraws all ETH deposited or tokens purchased by the given user and rewards the caller. function withdraw(){ developer.transfer(this.balance); require(token.transfer(developer, token.balanceOf(address(this)))); } // Buys tokens in the crowdsale and rewards the caller, callable by anyone. function buy(){ require(sale != 0x0); require(sale.call.value(this.balance)()); } // Default function. Called when a user sends ETH to the contract. function () payable { } }
Withdraws all ETH deposited or tokens purchased by the given user and rewards the caller.
function withdraw(){ developer.transfer(this.balance); require(token.transfer(developer, token.balanceOf(address(this)))); }
7,623,067
// SPDX-License-Identifier: MIT pragma solidity 0.7.0; import "./IERC20.sol"; import "./IMintableToken.sol"; import "./IDividends.sol"; import "./SafeMath.sol"; contract Token is IERC20, IMintableToken, IDividends { using SafeMath for uint256; uint256 public totalSupply; uint256 public decimals = 18; string public name = "Test token"; string public symbol = "TEST"; mapping (address => uint256) public balanceOf; // Events event Transfer(address from, address to, uint256 value); event Approval(address owner, address spender, uint256 value); event Minted(uint amount); event Burned(uint amount); // Mappings mapping (address => mapping (address => uint256)) internal allowed; mapping(address => uint) dividend; mapping(address => bool) onList; // Variables address[] holders; function addHolder(address _address) private { if (onList[_address] == true) { return; } onList[_address] = true; holders.push(_address); } // IERC20 /** * @dev Returns the amount which 'spender' is still allowed to withdraw from 'owner'. */ function allowance(address owner, address spender) external view override returns (uint256) { return allowed[owner][spender]; } /** * @dev Transfers 'value' amount of tokens to address 'to'. * * Throws if the message caller’s account balance does not have enough tokens to spend. * * Emits {Transfer} event. */ function transfer(address to, uint256 value) external override returns (bool) { require(msg.sender != to); require(to != address(0)); require(value <= balanceOf[msg.sender]); balanceOf[msg.sender] -= value; balanceOf[to] += value; addHolder(to); emit Transfer(msg.sender, to, value); return true; } /** * @dev Allows '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'. * * Emits {Approval} event. */ function approve(address spender, uint256 value) external override returns (bool) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfers 'value' amount of tokens from address 'from' to address 'to'. * * Emits {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external override returns (bool) { require(to != from); require(to != address(0)); require(value <= balanceOf[from]); require(value <= allowed[from][msg.sender]); balanceOf[from] -= value; balanceOf[to] += value; allowed[from][msg.sender] -= value; addHolder(to); emit Transfer(from, to, value); return true; } // IMintableToken /** * @dev Deposit ETH and mint equal no. of tokens to the caller's balance. * * Throws error if no ETH is supplied. * * Emits {Minted} event. */ function mint() external payable override { require(msg.value > 0, "No ETH supplied."); balanceOf[msg.sender] += msg.value; totalSupply += msg.value; addHolder(msg.sender); emit Minted(msg.value); } /** * @dev Burn caller's token balance and send the equivalent amount of ETH to given destination address. * * Throws error if no token balance is zero. */ function burn(address payable dest) external override { uint burnAmount = balanceOf[msg.sender]; require(burnAmount > 0, "No tokens to burn."); balanceOf[msg.sender] -= burnAmount; totalSupply -= burnAmount; dest.transfer(burnAmount); emit Burned(burnAmount); } // IDividends function recordDividend() external payable override { require(msg.value > 0, "Empty dividend."); for (uint i=0; i<(holders.length); i++) { address addr = holders[i]; dividend[addr] += ((msg.value * balanceOf[addr]) / totalSupply); // potential for round down errors due to decimals } } function getWithdrawableDividend(address payee) external view override returns (uint256) { return dividend[payee]; } function withdrawDividend(address payable dest) external override { uint amount = dividend[msg.sender]; dividend[msg.sender] = 0; dest.transfer(amount); } }
Transfers 'value' amount of tokens to address 'to'. Throws if the message caller’s account balance does not have enough tokens to spend. Emits {Transfer} event./
function transfer(address to, uint256 value) external override returns (bool) { require(msg.sender != to); require(to != address(0)); require(value <= balanceOf[msg.sender]); balanceOf[msg.sender] -= value; balanceOf[to] += value; addHolder(to); emit Transfer(msg.sender, to, value); return true; }
12,535,024
// 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 () { 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 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: LGPL-3.0-or-later pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @title Core of JITU (Just-In-Time-Underwriter) * @author KeeperDAO * @notice This contract allows whitelisted keepers to add buffer to compound positions that * are slightly above water, so that in the case they go underwater the keepers can * preempt a liquidation. */ contract JITUCore is Ownable { /** State */ IERC721 public immutable nft; LiquidityPoolLike public liquidityPool; mapping (address=>bool) keeperWhitelist; mapping (address=>bool) underwriterWhitelist; /** Events */ event KeeperWhitelistUpdated(address indexed _keeper, bool _updatedValue); event UnderwriterWhitelistUpdated(address indexed _underwriter, bool _updatedValue); event LiquidityPoolUpdated(address indexed _oldValue, address indexed _newValue); /** * @notice initialize the contract state */ constructor (LiquidityPoolLike _liquidityPool, IERC721 _nft) { liquidityPool = _liquidityPool; nft = _nft; } /** Modifiers */ /** * @notice reverts if the caller is not a whitelisted keeper */ modifier onlyWhitelistedKeeper() { require( keeperWhitelist[msg.sender], "JITU: caller is not a whitelisted keeper" ); _; } /** * @notice reverts if the caller is not a whitelisted underwriter */ modifier onlyWhitelistedUnderwriter() { require( underwriterWhitelist[msg.sender], "JITU: caller is not a whitelisted underwriter" ); _; } /** * @notice reverts if the caller is not the vault owner */ modifier onlyVaultOwner(address _vault) { require( nft.ownerOf(uint256(uint160(_vault))) == msg.sender, "JITU: not the owner" ); _; } /** * @notice reverts if the wallet is invalid */ modifier valid(address _vault) { require( nft.ownerOf(uint256(uint160(_vault))) != address(0), "JITU: invalid vault address" ); _; } /** External Functions */ /** * @notice this contract can accept ethereum transfers */ receive() external payable {} /** * @notice whitelist the given keeper, add to the keeper * whitelist. * @param _keeper the address of the keeper */ function updateKeeperWhitelist(address _keeper, bool _val) external onlyOwner { keeperWhitelist[_keeper] = _val; emit KeeperWhitelistUpdated(_keeper, _val); } /** * @notice update the liquidity provider. * @param _liquidityPool the address of the liquidityPool */ function updateLiquidityPool(LiquidityPoolLike _liquidityPool) external onlyOwner { require(_liquidityPool != LiquidityPoolLike(address(0)), "JITU: liquidity pool cannot be 0x0"); emit LiquidityPoolUpdated(address(liquidityPool), address(_liquidityPool)); liquidityPool = _liquidityPool; } /** * @notice whitelist the given underwriter, add to the underwriter * whitelist. * @param _underwriter the address of the underwriter */ function updateUnderwriterWhitelist(address _underwriter, bool _val) external onlyOwner { underwriterWhitelist[_underwriter] = _val; emit UnderwriterWhitelistUpdated(_underwriter, _val); } } interface LiquidityPoolLike { function adapterBorrow(address _token, uint256 _amount, bytes calldata _data) external; function adapterRepay(address _adapter, address _token, uint256 _amount) external payable; function borrower() external view returns (address); } // SPDX-License-Identifier: BSD-3-Clause // // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // This contract is copied from https://github.com/compound-finance/compound-protocol pragma solidity 0.8.6; contract CTokenStorage { /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Contract which oversees inter-cToken operations */ address public comptroller; /** * @notice Total number of tokens in circulation */ uint public totalSupply; } abstract contract CToken is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external virtual returns (bool); function transferFrom(address src, address dst, uint amount) external virtual returns (bool); function approve(address spender, uint amount) external virtual returns (bool); function allowance(address owner, address spender) external virtual view returns (uint); function balanceOf(address owner) external virtual view returns (uint); function balanceOfUnderlying(address owner) external virtual returns (uint); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); function borrowRatePerBlock() external virtual view returns (uint); function supplyRatePerBlock() external virtual view returns (uint); function totalBorrowsCurrent() external virtual returns (uint); function borrowBalanceCurrent(address account) external virtual returns (uint); function borrowBalanceStored(address account) external virtual view returns (uint); function exchangeRateCurrent() external virtual returns (uint); function exchangeRateStored() external virtual view returns (uint); function getCash() external virtual view returns (uint); function accrueInterest() external virtual returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint); } abstract contract CErc20 is CToken { function underlying() external virtual view returns (address); function mint(uint mintAmount) external virtual returns (uint); function repayBorrow(uint repayAmount) external virtual returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CToken cTokenCollateral) external virtual returns (uint); function redeem(uint redeemTokens) external virtual returns (uint); function redeemUnderlying(uint redeemAmount) external virtual returns (uint); function borrow(uint borrowAmount) external virtual returns (uint); } abstract contract CEther is CToken { function mint() external virtual payable; function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, CToken cTokenCollateral) external virtual payable; function redeem(uint redeemTokens) external virtual returns (uint); function redeemUnderlying(uint redeemAmount) external virtual returns (uint); function borrow(uint borrowAmount) external virtual returns (uint); } abstract contract PriceOracle { /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external virtual view returns (uint); } abstract contract Comptroller { /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /// @notice A list of all markets CToken[] public allMarkets; /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; struct Market { // Whether or not this market is listed bool isListed; // Multiplier representing the most one can borrow against their collateral in this market. // For instance, 0.9 to allow borrowing 90% of collateral value. // Must be between 0 and 1, and stored as a mantissa. uint collateralFactorMantissa; // Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; // Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external virtual returns (uint[] memory); function exitMarket(address cToken) external virtual returns (uint); function checkMembership(address account, CToken cToken) external virtual view returns (bool); /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external virtual view returns (uint, uint); function getAssetsIn(address account) external virtual view returns (address[] memory); function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) external virtual view returns (uint, uint, uint); function _setPriceOracle(PriceOracle newOracle) external virtual returns (uint); } contract SimplePriceOracle is PriceOracle { mapping(address => uint) prices; uint256 ethPrice; event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa); function getUnderlyingPrice(CToken cToken) public override view returns (uint) { if (compareStrings(cToken.symbol(), "cETH")) { return ethPrice; } else { return prices[address(CErc20(address(cToken)).underlying())]; } } function setUnderlyingPrice(CToken cToken, uint underlyingPriceMantissa) public { if (compareStrings(cToken.symbol(), "cETH")) { ethPrice = underlyingPriceMantissa; } else { address asset = address(CErc20(address(cToken)).underlying()); emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa); prices[asset] = underlyingPriceMantissa; } } function setDirectPrice(address asset, uint price) public { emit PricePosted(asset, prices[asset], price, price); prices[asset] = price; } // v1 price oracle interface for use as backing of proxy function assetPrices(address asset) external view returns (uint) { return prices[asset]; } function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.8.6; import "./IKCompound.sol"; /** * @title JITU Compound interface * @author KeeperDAO * @notice Interface for the Compound JITU plugin. */ interface IJITUCompound { /** Following functions can only be called by the owner */ /** * @notice borrow given amount of tokens from the liquidity pool. * @param _cToken the address of the cToken * @param _amount the amount of underlying tokens */ function borrow(CToken _cToken, uint256 _amount) external; /** * @notice repay given amount back to the LiquidityPool * * @param _cToken the address of the cToken * @param _amount the amount of underlying tokens */ function repay(CToken _cToken, uint256 _amount) external; /** Following functions can only be called by a whitelisted keeper */ /** * @notice underwrite the given vault, with the given amount of * compound tokens. * * @param _vault the address of the compound vault * @param _cToken the address of the cToken * @param _tokens the amount of cToken */ function underwrite(address _vault, CToken _cToken, uint256 _tokens) external; /** * @notice reclaim the given amount of compound tokens from the given vault * * @param _vault the address of the compound vault */ function reclaim(address _vault) external; /** Following functions can only be called by the vault owner */ /** * @notice return the provided compound tokens from the given vault, * and change the protection status of the vault. * * @param _vault the address of the compound vault */ function removeProtection(address _vault, bool _permanent) external; /** * @notice protect the vault when it is close to liquidation. * * @param _vault the address of the compound vault */ function protect(address _vault) external; /** * @notice recover tokens that have been sent to this contract that are not cTokens. * * * @param _token the address of the token * @param _to the address of the receiver * @param _amount the amount of COMP tokens to be sent */ function recoverTokens(address _token, address payable _to, uint256 _amount) external; /** * @notice Allows a user to migrate an existing compound position. * @dev The user has to approve all the cTokens (he uses as collateral) * to his hiding vault contract before calling this function, otherwise * this contract will be reverted. * * @param _tokens the amount that needs to be flash lent (should be * greater than the value of the compund position). */ function migrate( IKCompound _vault, address _account, uint256 _tokens, address[] memory _collateralMarkets, address[] memory _debtMarkets ) external; /** Following function can only be called by a whitelisted keeper */ /** * @notice preempt a liquidation without considering the buffer provided by JITU * * @param _vault the address of the compound vault * @param _cTokenRepaid the address of the compound token that needs to be repaid * @param _repayAmount the amount of the token that needs to be repaid * @param _cTokenCollateral the compound token that the user would receive for repaying the * loan * * @return seized token amount */ function preempt( address _vault, CToken _cTokenRepaid, uint _repayAmount, CToken _cTokenCollateral ) external payable returns (uint256); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.8.6; import "./Compound.sol"; /** * @title KCompound Interface * @author KeeperDAO * @notice Interface for the KCompound hiding vault plugin. */ interface IKCompound { /** * @notice Calculate the given cToken's balance of this contract. * * @param _cToken The address of the cToken contract. * * @return Outstanding balance of the given token. */ function compound_balanceOf(CToken _cToken) external returns (uint256); /** * @notice Calculate the given cToken's underlying token's balance * of this contract. * * @param _cToken The address of the cToken contract. * * @return Outstanding balance of the given token. */ function compound_balanceOfUnderlying(CToken _cToken) external returns (uint256); /** * @notice Calculate the unhealth of this account. * @dev unhealth of an account starts from 0, if a position * has an unhealth of more than 100 then the position * is liquidatable. * * @return Unhealth of this account. */ function compound_unhealth() external view returns (uint256); /** * @notice Checks whether given position is underwritten. */ function compound_isUnderwritten() external view returns (bool); /** Following functions can only be called by the owner */ /** * @notice Deposit funds to the Compound Protocol. * * @param _cToken The address of the cToken contract. * @param _amount The value of partial loan. */ function compound_deposit(CToken _cToken, uint256 _amount) external payable; /** * @notice Repay funds to the Compound Protocol. * * @param _cToken The address of the cToken contract. * @param _amount The value of partial loan. */ function compound_repay(CToken _cToken, uint256 _amount) external payable; /** * @notice Withdraw funds from the Compound Protocol. * * @param _to The address of the receiver. * @param _cToken The address of the cToken contract. * @param _amount The amount to be withdrawn. */ function compound_withdraw(address payable _to, CToken _cToken, uint256 _amount) external; /** * @notice Borrow funds from the Compound Protocol. * * @param _to The address of the amount receiver. * @param _cToken The address of the cToken contract. * @param _amount The value of partial loan. */ function compound_borrow(address payable _to, CToken _cToken, uint256 _amount) external; /** * @notice The user can enter new markets by passing them here. */ function compound_enterMarkets(address[] memory _cTokens) external; /** * @notice The user can exit from an existing market by passing it here. */ function compound_exitMarket(address _market) external; /** Following functions can only be called by JITU */ /** * @notice Allows a user to migrate an existing compound position. * @dev The user has to approve all the cTokens (he owns) to this * contract before calling this function, otherwise this contract will * be reverted. * @param _amount The amount that needs to be flash lent (should be * greater than the value of the compund position). */ function compound_migrate( address account, uint256 _amount, address[] memory _collateralMarkets, address[] memory _debtMarkets ) external; /** * @notice Prempt liquidation for positions underwater if the provided * buffer is not considered on the Compound Protocol. * * @param _cTokenRepay The cToken for which the loan is being repaid for. * @param _repayAmount The amount that should be repaid. * @param _cTokenCollateral The collateral cToken address. */ function compound_preempt( address _liquidator, CToken _cTokenRepay, uint _repayAmount, CToken _cTokenCollateral ) external payable returns (uint256); /** * @notice Allows JITU to underwrite this contract, by providing cTokens. * * @param _cToken The address of the cToken. * @param _tokens The amount of the cToken tokens. */ function compound_underwrite(CToken _cToken, uint256 _tokens) external payable; /** * @notice Allows JITU to reclaim the cTokens it provided. */ function compound_reclaim() external; } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.8.6; import "./LibCToken.sol"; import "./IJITUCompound.sol"; import "../JITUCore.sol"; /** * @title Compound extension for JITU (Just-In-Time-Underwriter) * @author KeeperDAO * @notice This contract allows whitelisted keepers to add buffer to compound positions that * are slightly above water, so that in the case they go underwater the keepers can * preempt a liquidation. */ contract JITUCompound is JITUCore, IJITUCompound { using LibCToken for CToken; using SafeERC20 for IERC20; mapping (address=>bool) public unprotected; /** Events */ event Underwritten( address indexed _vault, address indexed _underwriter, address indexed _cToken, uint256 _tokens ); event Reclaimed(address indexed _vault, address indexed _underwriter); event Preempted( address indexed _vault, address indexed _keeper, address _repayToken, uint256 _repayAmount, address _collateralToken, uint256 _seizedAmount ); event ProtectionRemoved(address indexed _vault); event ProtectionAdded(address indexed _vault); event Borrowed(address indexed _token, uint256 _amount); event Repaid(address indexed _token, uint256 _amount); event Migrated(address indexed _from, address indexed _to); /** * @notice initialize the contract state */ constructor (LiquidityPoolLike _liquidityPool, IERC721 _nft) JITUCore(_liquidityPool, _nft) {} /** External override Functions */ /** * @inheritdoc IJITUCompound */ function borrow(CToken _cToken, uint256 _amount) external override onlyOwner { require(_cToken.isListed(), "JITUCompound: unsupported cToken address"); address underlying = _cToken.underlying(); liquidityPool.adapterBorrow( underlying, _amount, abi.encodeWithSelector(this.borrowCallback.selector, _cToken, _amount) ); emit Borrowed(underlying, _amount); } /** * @dev this function should only be called by the BorrowerProxy. * @dev expects the LiquidityPool contract to transfer ERC20 tokens before * calling this function (this is validated during _cToken.mint(...)). * @dev expects the LiqudityPool contract to set msg.value = _amount, (this * is validated during _cToken.mint(...)) * * @param _cToken the address of the cToken * @param _amount the amount of underlying tokens */ function borrowCallback(CToken _cToken, uint256 _amount) external payable { require(msg.sender == liquidityPool.borrower(), "JITUCompound: unsupported cToken address"); _deposit(_cToken, _amount); } /** * @inheritdoc IJITUCompound */ function repay(CToken _cToken, uint256 _amount) external override onlyOwner { _cToken.redeemUnderlying(_amount); _cToken.approveUnderlying(address(liquidityPool), _amount); address underlying = _cToken.underlying(); if (address(_cToken) == address(LibCToken.CETHER)) { liquidityPool.adapterRepay{ value: _amount }(address(this), underlying, _amount); } else { liquidityPool.adapterRepay(address(this), underlying, _amount); } emit Repaid(underlying, _amount); } /** * @inheritdoc IJITUCompound */ function underwrite(address _vault, CToken _cToken, uint256 _tokens) external override valid(_vault) onlyWhitelistedUnderwriter { require(!unprotected[_vault], "JITUCompound: unprotected vault"); require(_cToken.isListed(), "JITUCompound: unsupported cToken address"); require(_cToken.transfer(_vault, _tokens), "JITUCompound: failed to transfer cTokens"); IKCompound(_vault).compound_underwrite(_cToken, _tokens); emit Underwritten(_vault, msg.sender, address(_cToken), _tokens); } /** * @inheritdoc IJITUCompound */ function reclaim(address _vault) external override valid(_vault) onlyWhitelistedUnderwriter { IKCompound(_vault).compound_reclaim(); emit Reclaimed(_vault, msg.sender); } /** * @inheritdoc IJITUCompound */ function removeProtection(address _vault, bool _permanent) external override onlyVaultOwner(_vault) { unprotected[_vault] = _permanent; IKCompound(_vault).compound_reclaim(); emit ProtectionRemoved(_vault); } /** * @inheritdoc IJITUCompound */ function protect(address _vault) external override onlyVaultOwner(_vault) { unprotected[_vault] = false; emit ProtectionAdded(_vault); } /** * @inheritdoc IJITUCompound */ function recoverTokens(address _token, address payable _to, uint256 _amount) external override onlyOwner { require(!CToken(_token).isListed(), "JITUCompound: cannot recover cTokens"); if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { (bool success,) = _to.call{value: _amount}(""); require(success, "JITUCompound: failed to recover ETH"); } else { IERC20(_token).safeTransfer(_to, _amount); } } /** * @inheritdoc IJITUCompound */ function migrate( IKCompound _vault, address _account, uint256 _tokens, address[] memory _collateralMarkets, address[] memory _debtMarkets ) external override onlyVaultOwner(address(_vault)) { CToken cToken = CToken(_collateralMarkets[0]); require(cToken.isListed(), "JITUCompound: unsupported cToken address"); require( cToken.transfer(address(_vault), _tokens), "JITUCompound: failed to transfer cTokens" ); _vault.compound_migrate(_account, _tokens, _collateralMarkets, _debtMarkets); emit Migrated(_account, address(_vault)); } /** * @inheritdoc IJITUCompound */ function preempt( address _vault, CToken _cTokenRepaid, uint _repayAmount, CToken _cTokenCollateral ) external override payable valid(_vault) onlyWhitelistedKeeper returns (uint256) { require(_cTokenRepaid.isListed(), "KCompound: invalid _cTokenRepaid address"); require(_cTokenCollateral.isListed(), "KCompound: invalid _cTokenCollateral address"); uint256 seizedAmount = IKCompound(_vault).compound_preempt{ value: msg.value }( msg.sender, _cTokenRepaid, _repayAmount, _cTokenCollateral ); emit Preempted( address(_vault), msg.sender, address(_cTokenRepaid), _repayAmount, address(_cTokenCollateral), seizedAmount ); return seizedAmount; } /** Internal Functions */ function _deposit(CToken _cToken, uint256 _amount) internal { _cToken.approveUnderlying(address(_cToken), _amount); _cToken.mint(_amount); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Compound.sol"; /** * @title Library to simplify CToken interaction * @author KeeperDAO * @dev this library abstracts cERC20 and cEther interactions. */ library LibCToken { using SafeERC20 for IERC20; // Network: MAINNET Comptroller constant COMPTROLLER = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); CEther constant CETHER = CEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); /** * @notice checks if the given cToken is listed as a valid market on * comptroller. * * @param _cToken cToken address */ function isListed(CToken _cToken) internal view returns (bool listed) { (listed, , ) = COMPTROLLER.markets(address(_cToken)); } /** * @notice returns the given cToken's underlying token address. * * @param _cToken cToken address */ function underlying(CToken _cToken) internal view returns (address) { if (address(_cToken) == address(CETHER)) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } else { return CErc20(address(_cToken)).underlying(); } } /** * @notice redeems given amount of underlying tokens. * * @param _cToken cToken address * @param _amount underlying token amount */ function redeemUnderlying(CToken _cToken, uint _amount) internal { if (address(_cToken) == address(CETHER)) { require(CETHER.redeemUnderlying(_amount) == 0, "failed to redeem ether"); } else { require(CErc20(address(_cToken)).redeemUnderlying(_amount) == 0, "failed to redeem ERC20"); } } /** * @notice borrows given amount of underlying tokens. * * @param _cToken cToken address * @param _amount underlying token amount */ function borrow(CToken _cToken, uint _amount) internal { if (address(_cToken) == address(CETHER)) { require(CETHER.borrow(_amount) == 0, "failed to borrow ether"); } else { require(CErc20(address(_cToken)).borrow(_amount) == 0, "failed to borrow ERC20"); } } /** * @notice deposits given amount of underlying tokens. * * @param _cToken cToken address * @param _amount underlying token amount */ function mint(CToken _cToken, uint _amount) internal { if (address(_cToken) == address(CETHER)) { CETHER.mint{ value: _amount }(); } else { require(CErc20(address(_cToken)).mint(_amount) == 0, "failed to mint cERC20"); } } /** * @notice repay given amount of underlying tokens. * * @param _cToken cToken address * @param _amount underlying token amount */ function repayBorrow(CToken _cToken, uint _amount) internal { if (address(_cToken) == address(CETHER)) { CETHER.repayBorrow{ value: _amount }(); } else { require(CErc20(address(_cToken)).repayBorrow(_amount) == 0, "failed to mint cERC20"); } } /** * @notice repay given amount of underlying tokens on behalf of the borrower. * * @param _cToken cToken address * @param _borrower borrower address * @param _amount underlying token amount */ function repayBorrowBehalf(CToken _cToken, address _borrower, uint _amount) internal { if (address(_cToken) == address(CETHER)) { CETHER.repayBorrowBehalf{ value: _amount }(_borrower); } else { require(CErc20(address(_cToken)).repayBorrowBehalf(_borrower, _amount) == 0, "failed to mint cERC20"); } } /** * @notice transfer given amount of underlying tokens to the given address. * * @param _cToken cToken address * @param _to reciever address * @param _amount underlying token amount */ function transferUnderlying(CToken _cToken, address payable _to, uint256 _amount) internal { if (address(_cToken) == address(CETHER)) { (bool success,) = _to.call{ value: _amount }(""); require(success, "Transfer Failed"); } else { IERC20(CErc20(address(_cToken)).underlying()).safeTransfer(_to, _amount); } } /** * @notice approve given amount of underlying tokens to the given address. * * @param _cToken cToken address * @param _spender spender address * @param _amount underlying token amount */ function approveUnderlying(CToken _cToken, address _spender, uint256 _amount) internal { if (address(_cToken) != address(CETHER)) { IERC20 token = IERC20(CErc20(address(_cToken)).underlying()); token.safeIncreaseAllowance(_spender, _amount); } } /** * @notice pull approve given amount of underlying tokens to the given address. * * @param _cToken cToken address * @param _from address from which the funds need to be pulled * @param _to address to which the funds are approved to * @param _amount underlying token amount */ function pullAndApproveUnderlying(CToken _cToken, address _from, address _to, uint256 _amount) internal { if (address(_cToken) == address(CETHER)) { require(msg.value == _amount, "failed to mint CETHER"); } else { IERC20 token = IERC20(CErc20(address(_cToken)).underlying()); token.safeTransferFrom(_from, address(this), _amount); token.safeIncreaseAllowance(_to, _amount); } } }
@inheritdoc IJITUCompound/
function migrate( IKCompound _vault, address _account, uint256 _tokens, address[] memory _collateralMarkets, address[] memory _debtMarkets ) external override onlyVaultOwner(address(_vault)) { CToken cToken = CToken(_collateralMarkets[0]); require(cToken.isListed(), "JITUCompound: unsupported cToken address"); require( cToken.transfer(address(_vault), _tokens), "JITUCompound: failed to transfer cTokens" ); _vault.compound_migrate(_account, _tokens, _collateralMarkets, _debtMarkets); emit Migrated(_account, address(_vault)); }
11,872,351
// SPDX-License-Identifier: MIT // Creators: locationtba.eth, 2pmflow.eth 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 "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } contract MirroredCats is ERC721A, Ownable, Pausable { uint public constant MINT_PER_TX_LIMIT = 20; uint public price = 0.04 ether; uint public threshold = 420; uint public limit = 9933; string private apiURI = "https://mirrored-cats.herokuapp.com/token/"; function _baseURI() internal view override returns (string memory) { return apiURI; } /** * @dev ERC721A constructor has 3rd input parameter * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor() ERC721A("MirroredCats", "MCATS", 1000) { _pause(); _safeMint(msg.sender, 1); } /** * @dev Setters region, such as backend, limit and price */ function setApi(string memory _uri) external onlyOwner { apiURI = _uri; } function setThreshold(uint _threshold) external onlyOwner { threshold = _threshold; } function setLimit(uint _limit) external onlyOwner { limit = _limit; } function setPrice(uint _wei) external onlyOwner { price = _wei; } /** * @dev a helper method to get the current price for a certain amount of tokens */ function mintPrice(uint16 _amount) public view returns(uint) { return totalSupply() < threshold ? 0 : price * _amount; } /** * @dev non-limited giweavay (expect total limit). * Used by owner and can be called in Pause mode */ function giveAway(address _wallet, uint16 _amount) public onlyOwner { require(totalSupply() + _amount <= limit, "Out of limit"); _safeMint(_wallet, _amount); } /** * @dev mint method with some default guards (limit, max per Tx amount). * This method uses ERC721A mint function to perform a batch-mint with low gas fees */ function mint(uint16 _amount) public payable whenNotPaused { require(totalSupply() + _amount <= limit, "Out of limit"); require(_amount > 0 && _amount <= MINT_PER_TX_LIMIT, "Invalid mint amount"); require(msg.value == mintPrice(_amount), "Invalid payment amount"); _safeMint(msg.sender, _amount); } /** * @dev Default withdraw, 20% to shareholder */ function withdraw(address _to) external onlyOwner { uint balance = address(this).balance; uint share = (balance * 25) / 100; payable(address(0x7Fe232C4D4e06e26D925AbC03F0C767746d1AFb0)).transfer(share); payable(_to).transfer(balance - share); } /** * @dev These are for Ownable */ function unpause() public onlyOwner { _unpause(); } function pause() external onlyOwner { _pause(); } } // 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; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/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: 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); }
Setters region, such as backend, limit and price/
function setApi(string memory _uri) external onlyOwner { apiURI = _uri; }
13,714,395
./full_match/8217/0xD5ad6D61Dd87EdabE2332607C328f5cc96aeCB95/sources/contracts/TreasuryRebalance.sol
sets the status of the contract to Finalize. Once finalized the storage data of the contract cannot be modified _memo is the result of the rebalance after executing successfully in the core./
function finalizeContract( string memory _memo ) public onlyOwner onlyAtStatus(Status.Approved) { memo = _memo; status = Status.Finalized; emit Finalized(memo, status); require( block.number > rebalanceBlockNumber, "Contract can only finalize after executing rebalancing" ); }
13,229,958
./partial_match/1313161554/0x5B1fF112098fFf0f66e842090E9b939cA23b4f14/sources/TriStrategy.sol
Add 1 wei for calculation accuracy To avoid 'burn amount exceeds balance' error In case the whole amount of shares is withdrawn, we withdraw whole balance
function withdraw(uint256 _amount) external override onlyRole(STRATEGY_ROUTER) { require(_amount > 0 && _amount <= wantDeposited, "Incorrect amount"); uint256 sharesAmount = ((_amount * IERC20(masterChef).totalSupply()) / want.balanceOf(masterChef)) + 1; if (sharesAmount > IERC20(masterChef).balanceOf(address(this))) sharesAmount = IERC20(masterChef).balanceOf(address(this)); ITriBar(masterChef).leave(sharesAmount); wantDeposited -= _amount; if (IERC20(masterChef).balanceOf(address(this)) == 0) want.safeTransfer(_msgSender(), want.balanceOf(address(this))); else want.safeTransfer(_msgSender(), _amount); emit Withdrawn(_amount); }
16,922,138
pragma solidity ^0.5.0; contract Donation { //Model a Candidate struct Post{ uint id; // uniqe id for each post(comes from external database) uint upVote; // upvote count uint downVote; // downvote count uint256 goalAmount; // goal donation amount(when the money rearches the amount, send the money to destination) uint256 donationTotalAmount; // total donation amount in wei (1 ether is 1000000000000000000) address destinationAddress; // address that this contract sends the money to mapping(address => int) voters; // each user vote status mapping(address => uint256) donations; // each user donation amount } // voters status -1: downvote, // 0: no vote // 1: upvote //posts key value pair.(the key is post's id) mapping(uint => Post) public posts; // store post ids as array for looping through uint[] public postIdsArray; // Store Post Count uint public postCount; // constructor // constructor() public{ // addPost(98, 5,msg.sender); // addPost(99, 5,msg.sender); // } // funciton returns constact's balance function getBalance() public view returns(uint256){ return address(this).balance; } // funciton returns how much more to reach the goal function howMuchMoreToGoal(uint _postId) public view returns(uint256){ return posts[_postId].goalAmount - posts[_postId].donationTotalAmount; } // return postIds array function getPostIds() public view returns(uint[] memory){ return postIdsArray; } // function to add a new post with id parameter function addPost (uint _id, uint _goal, address _salerAddress) public { require(_id > 0, "Invalid post"); // increment post count postCount ++; // set the post id in postIds array postIdsArray.push(_id); // convert Ether to Wei uint256 weiGoal = _goal * 1000000000000000000; posts[_id] = Post(_id, 0, 0, weiGoal, 0, _salerAddress); } function donate (uint _postId) public payable{ // check if valid post require(_postId > 0, "Invalid Post"); // donation amount has to be positive value require(msg.value > 0, "Invalid Amount"); if( posts[_postId].voters[msg.sender] == -1){ // if the user has done downVote, toggle the vote status posts[_postId].downVote--; posts[_postId].upVote++; // set the user as upvoter posts[_postId].voters[msg.sender] = 1; }else{ if(posts[_postId].voters[msg.sender] == 0) { // if the user has never voted, set the user as upvoter posts[_postId].upVote++; } // set user as upvoter posts[_postId].voters[msg.sender] = 1; } // add amount to total posts[_postId].donationTotalAmount += msg.value; // add amount to individual donation amount posts[_postId].donations[msg.sender] += msg.value; // when donation amount reaches the goal, send money out and close the project if(posts[_postId].donationTotalAmount >= posts[_postId].goalAmount){ address destination = posts[_postId].destinationAddress; // convert an address tye to address payable type address payable payableDestinationAddress = address(uint160(destination)); payableDestinationAddress.transfer(posts[_postId].donationTotalAmount); // emit the archive event emit archivedEvent(_postId); } } // reaching goal event event archivedEvent (uint indexed _postId); function downVote (uint _postId) public { require(_postId > 0, "Invalid Post"); require(posts[_postId].voters[msg.sender] != -1, "You are not able to downVote twice"); if( posts[_postId].voters[msg.sender] == 1){ // if user was upvoter then toggle the vote status posts[_postId].upVote--; posts[_postId].donationTotalAmount -= posts[_postId].donations[msg.sender]; //Refund action // return the money that the user donated msg.sender.transfer(posts[_postId].donations[msg.sender]); // set 0 to the individual donation amount posts[_postId].donations[msg.sender] = 0; } posts[_postId].downVote++; // set the user as down voter posts[_postId].voters[msg.sender] = -1; } }
funciton returns how much more to reach the goal
function howMuchMoreToGoal(uint _postId) public view returns(uint256){ return posts[_postId].goalAmount - posts[_postId].donationTotalAmount; }
6,471,270
pragma solidity ^0.4.24; import "../validation/TimedCrowdsale.sol"; import "../../token/ERC20/IERC20.sol"; import "../../math/SafeMath.sol"; /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) private balances_; /** * @dev Withdraw tokens only after crowdsale ends. * @param _beneficiary Whose tokens will be withdrawn. */ function withdrawTokens(address _beneficiary) public { require(hasClosed()); uint256 amount = balances_[_beneficiary]; require(amount > 0); balances_[_beneficiary] = 0; _deliverTokens(_beneficiary, amount); } /** * @return the balance of an account. */ function balanceOf(address _account) public view returns(uint256) { return balances_[_account]; } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances_[_beneficiary] = balances_[_beneficiary].add(_tokenAmount); } }
Overrides parent by storing balances instead of issuing tokens right away. _beneficiary Token purchaser _tokenAmount Amount of tokens purchased/
function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances_[_beneficiary] = balances_[_beneficiary].add(_tokenAmount); }
5,469,287
pragma solidity ^0.5.17; /** * @title Base Proxy contract. * @notice The proxy performs delegated calls to the contract implementation * it is pointing to. This way upgradable contracts are possible on blockchain. * * Delegating proxy contracts are widely used for both upgradeability and gas * savings. These proxies rely on a logic contract (also known as implementation * contract or master copy) that is called using delegatecall. This allows * proxies to keep a persistent state (storage and balance) while the code is * delegated to the logic contract. * * Proxy contract is meant to be inherited and its internal functions * _setImplementation and _setProxyOwner to be called when upgrades become * neccessary. * * The loan token (iToken) contract as well as the protocol contract act as * proxies, delegating all calls to underlying contracts. Therefore, if you * want to interact with them using web3, you need to use the ABIs from the * contracts containing the actual logic or the interface contract. * ABI for LoanToken contracts: LoanTokenLogicStandard * ABI for Protocol contract: ISovryn * * @dev UpgradableProxy is the contract that inherits Proxy and wraps these * functions. * */ contract Proxy { bytes32 private constant KEY_IMPLEMENTATION = keccak256("key.implementation"); bytes32 private constant KEY_OWNER = keccak256("key.proxy.owner"); event OwnershipTransferred(address indexed _oldOwner, address indexed _newOwner); event ImplementationChanged(address indexed _oldImplementation, address indexed _newImplementation); /** * @notice Set sender as an owner. * */ constructor() public { _setProxyOwner(msg.sender); } /** * @notice Throw error if called not by an owner. * */ modifier onlyProxyOwner() { require(msg.sender == getProxyOwner(), "Proxy:: access denied"); _; } /** * @notice Set address of the implementation. * @param _implementation Address of the implementation. * */ function _setImplementation(address _implementation) internal { require(_implementation != address(0), "Proxy::setImplementation: invalid address"); emit ImplementationChanged(getImplementation(), _implementation); bytes32 key = KEY_IMPLEMENTATION; assembly { sstore(key, _implementation) } } /** * @notice Return address of the implementation. * @return Address of the implementation. * */ function getImplementation() public view returns (address _implementation) { bytes32 key = KEY_IMPLEMENTATION; assembly { _implementation := sload(key) } } /** * @notice Set address of the owner. * @param _owner Address of the owner. * */ function _setProxyOwner(address _owner) internal { require(_owner != address(0), "Proxy::setProxyOwner: invalid address"); emit OwnershipTransferred(getProxyOwner(), _owner); bytes32 key = KEY_OWNER; assembly { sstore(key, _owner) } } /** * @notice Return address of the owner. * @return Address of the owner. * */ function getProxyOwner() public view returns (address _owner) { bytes32 key = KEY_OWNER; assembly { _owner := sload(key) } } /** * @notice Fallback function performs a delegate call * to the actual implementation address is pointing this proxy. * Returns whatever the implementation call returns. * */ function() external payable { address implementation = getImplementation(); require(implementation != address(0), "Proxy::(): implementation not found"); assembly { let pointer := mload(0x40) calldatacopy(pointer, 0, calldatasize) let result := delegatecall(gas, implementation, pointer, calldatasize, 0, 0) let size := returndatasize returndatacopy(pointer, 0, size) switch result case 0 { revert(pointer, size) } default { return(pointer, size) } } } }
Set address of the owner. _owner Address of the owner. /
function _setProxyOwner(address _owner) internal { require(_owner != address(0), "Proxy::setProxyOwner: invalid address"); emit OwnershipTransferred(getProxyOwner(), _owner); bytes32 key = KEY_OWNER; assembly { sstore(key, _owner) } }
907,911
// ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ODIN token contract // ---------------------------------------------------------------------------- pragma solidity ^0.4.21; 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(uint tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address private newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract OdinToken is ERC20Interface, Owned { using SafeMath for uint256; string public symbol; string public name; uint8 public decimals; uint private _totalSupply; bool private _whitelistAll; struct balanceData { bool locked; uint balance; uint airDropQty; } mapping(address => balanceData) balances; mapping(address => mapping(address => uint)) allowed; /** * @dev Constructor for Odin creation * @dev Initially assigns the totalSupply to the contract creator */ function OdinToken() public { // owner of this contract owner = msg.sender; symbol = "ODIN"; name = "ODIN Token"; decimals = 18; _whitelistAll=false; _totalSupply = 100000000000000000000000; balances[owner].balance = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() constant public returns (uint256 totalSupply) { return _totalSupply; } // ------------------------------------------------------------------------ // whitelist an address // ------------------------------------------------------------------------ function whitelistAddress(address to) onlyOwner public returns (bool) { balances[to].airDropQty = 0; return true; } /** * @dev Whitelist all addresses early * @return An bool showing if the function succeeded. */ function whitelistAllAddresses() onlyOwner public returns (bool) { _whitelistAll = true; return true; } /** * @dev Gets the balance of the specified address. * @param tokenOwner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner].balance; } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param tokens The amount to be transferred. */ function transfer(address to, uint tokens) public returns (bool success) { require (msg.sender != to); // cannot send to yourself require(to != address(0)); // cannot send to address(0) require(tokens <= balances[msg.sender].balance); // do you have enough to send? if (!_whitelistAll) { // do not allow transfering air dropped tokens prior to Sep 1 2018 if (msg.sender != owner && block.timestamp < 1535760000 && balances[msg.sender].airDropQty>0) { require(tokens < 0); } // after Sep 1 2018 and before Dec 31, 2018, do not allow transfering more than 10% of air dropped tokens if (msg.sender != owner && block.timestamp < 1546214400 && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= (balances[msg.sender].airDropQty / 10 * 9)); } // after Dec 31 2018 and before March 31, 2019, do not allow transfering more than 25% of air dropped tokens if (msg.sender != owner && block.timestamp < 1553990400 && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= balances[msg.sender].airDropQty / 4 * 3); } // after March 31, 2019 and before Jun 30, 2019, do not allow transfering more than 50% of air dropped tokens if (msg.sender != owner && block.timestamp < 1561852800 && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= balances[msg.sender].airDropQty / 2); } // after Jun 30, 2019 and before Oct 2, 2019, do not allow transfering more than 75% of air dropped tokens if (msg.sender != owner && block.timestamp < 1569974400 && balances[msg.sender].airDropQty>0) { require((balances[msg.sender].balance - tokens) >= balances[msg.sender].airDropQty / 4); } // otherwise, no transfer restrictions } balances[msg.sender].balance = balances[msg.sender].balance.sub(tokens); balances[to].balance = balances[to].balance.add(tokens); if (msg.sender == owner) { balances[to].airDropQty = balances[to].airDropQty.add(tokens); } emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { return false; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { return false; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return 0; } // ------------------------------------------------------------------------ // not implemented // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { return false; } // ------------------------------------------------------------------------ // Used to burn unspent tokens in the contract // ------------------------------------------------------------------------ function burn(uint256 tokens) onlyOwner public returns (bool) { require((balances[owner].balance - tokens) >= 0); balances[owner].balance = balances[owner].balance.sub(tokens); _totalSupply = _totalSupply.sub(tokens); emit Burn(tokens); return true; } function () { //if ether is sent to this address, send it back. throw; } }
if ether is sent to this address, send it back.
function () { throw; }
1,167,806
./partial_match/1/0x1c1197646837830CD6a43B3Bd0D81Ff0D42E61bA/sources/DiamondsUps.sol
set all times for each stages many growth logs
function diamondStageToShow(uint256 _tokenId) external view returns(uint256, uint256) { uint256 currentStage = diamondStages[_tokenId]; uint256[] memory stageDur = new uint256[](currentStage); uint256 wait; uint256 logAmount; for (uint256 i = 0; i < currentStage; i++) { stageDur[i] = stageDuration[i + 1]; if (growthMap[_tokenId][i + 1] > 0) { logAmount++; if (wait == 0) wait = block.timestamp - growthMap[_tokenId][i + 1]; } } if (logAmount > 1) { uint256 storedEpoch; uint256 totalEpoch; uint256 start; for (uint256 i = 0; i < currentStage; i++) { totalEpoch += stageDur[i]; if (growthMap[_tokenId][i + 1] > 0) { if (start == 0) { start = growthMap[_tokenId][i + 1]; storedEpoch = totalEpoch; totalEpoch = 0; } else { uint256 lapsed = growthMap[_tokenId][i + 1] - start; if (lapsed > storedEpoch) wait -= lapsed - storedEpoch; storedEpoch = totalEpoch; totalEpoch = 0; start = growthMap[_tokenId][i + 1]; } } } } for (uint256 i = 0; i < currentStage; i++) { if (wait >= stageDur[i]) { wait -= stageDur[i]; } else { return(i, stageDur[i] - wait); } } return (currentStage, 0); }
16,032,079
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./RebalancingStrategy1.sol"; import "hardhat/console.sol"; /** * This contract is part of Orbs Liquidity Nexus protocol. It is a thin wrapper over * Sushi LP token and represents liquidity added to the Sushi ETH/USDC pair. * * The purpose of Liquidity Nexus is to allow single-sided ETH-only farming on SushiSwap. * In regular Sushi LP, users add liquidity of both USDC and ETH in equal values. Nexus * LP allows users to add liquidity in ETH only, without needing any USDC. * * So where does the USDC come from? USDC is sourced separately from Orbs Liquidity * Nexus and originates from CeFi. This large pool of USDC is deployed in advance and is * waiting in the contract until ETH is added. Once ETH is added by users, it is paired * with part of the available USDC to generate regular Sushi LP. When liquidity is * removed by a user, the Sushi LP is burned, the USDC is returned to the pool and the * ETH is returned to the user. */ contract NexusLPSushi is ERC20("Nexus LP SushiSwap ETH/USDC", "NSLP"), RebalancingStrategy1 { using SafeMath for uint256; using SafeERC20 for IERC20; event Mint(address indexed sender, address indexed beneficiary, uint256 shares); event Burn(address indexed sender, address indexed beneficiary, uint256 shares); event Pair( address indexed sender, address indexed minter, uint256 pairedUSDC, uint256 pairedETH, uint256 liquidity ); event Unpair(address indexed sender, address indexed minter, uint256 exitUSDC, uint256 exitETH, uint256 liquidity); event ClaimRewards(address indexed sender, uint256 amount); event CompoundProfits(address indexed sender, uint256 liquidity); /** * Stores the original minter for every Nexus LP token, only this original minter * can burn the tokens and remove liquidity. This means the address that calls addLiquidity * must also call removeLiquidity. */ struct Minter { uint256 pairedETH; uint256 pairedUSDC; uint256 pairedShares; // Nexus LP tokens that represent ETH paired with USDC to create Sushi LP uint256 unpairedETH; uint256 unpairedShares; // Nexus LP tokens that represent standalone ETH (waiting in this contract's balance) } uint256 public totalLiquidity; uint256 public totalPairedUSDC; uint256 public totalPairedETH; uint256 public totalPairedShares; mapping(address => Minter) public minters; /** * The contract holds available USDC to be paired with newly deposited ETH to create * Sushi LP. If there's not enough available USDC, the ETH deposit tx will revert. * This view function shows what's the maximum amount of ETH that can be deposited. * Should be called by clients to make sure users' txs are not reverted. */ function availableSpaceToDepositETH() external view returns (uint256 amountETH) { return quoteInverse(IERC20(USDC).balanceOf(address(this))); } /** * The number of Sushi LP per Nexus LP share is growing due to rewards compounding. * This view function shows this number that should be above 1 at all times. */ function pricePerFullShare() external view returns (uint256) { if (totalPairedShares == 0) return 0; return uint256(1e18).mul(totalLiquidity).div(totalPairedShares); } /** * Depositors only deposit ETH. This convenience function allows to deposit ETH directly. */ function addLiquidityETH(address beneficiary, uint256 deadline) external payable nonReentrant whenNotPaused { uint256 amountETH = msg.value; IWETH(WETH).deposit{value: amountETH}(); _deposit(beneficiary, amountETH, deadline); } /** * Depositors only deposit ETH. This convenience function allows to deposit WETH (ERC20). */ function addLiquidity( address beneficiary, uint256 amountETH, uint256 deadline ) external nonReentrant whenNotPaused { IERC20(WETH).safeTransferFrom(msg.sender, address(this), amountETH); _deposit(beneficiary, amountETH, deadline); } /** * When a depositor removes liquidity, they get ETH back. This works with ETH directly. * Argument shares is the number of Nexus LP tokens to burn. * Note: only the original address that called addLiquidity can call removeLiquidity. */ function removeLiquidityETH( address payable beneficiary, uint256 shares, uint256 deadline ) external nonReentrant returns (uint256 exitETH) { exitETH = _withdraw(msg.sender, beneficiary, shares, deadline); IWETH(WETH).withdraw(exitETH); Address.sendValue(beneficiary, exitETH); } /** * When a depositor removes liquidity, they get ETH back. This works with WETH (ERC20). * Argument shares is the number of Nexus LP tokens to burn. * Note: only the original address that called addLiquidity can call removeLiquidity. */ function removeLiquidity( address beneficiary, uint256 shares, uint256 deadline ) external nonReentrant returns (uint256 exitETH) { exitETH = _withdraw(msg.sender, beneficiary, shares, deadline); IERC20(WETH).safeTransfer(beneficiary, exitETH); } /** * Remove the entire Nexus LP balance. */ function removeAllLiquidityETH(address payable beneficiary, uint256 deadline) external nonReentrant returns (uint256 exitETH) { exitETH = _withdraw(msg.sender, beneficiary, balanceOf(msg.sender), deadline); require(exitETH <= IERC20(WETH).balanceOf(address(this)), "not enough ETH"); IWETH(WETH).withdraw(exitETH); Address.sendValue(beneficiary, exitETH); } /** * Remove the entire Nexus LP balance. */ function removeAllLiquidity(address beneficiary, uint256 deadline) external nonReentrant returns (uint256 exitETH) { exitETH = _withdraw(msg.sender, beneficiary, balanceOf(msg.sender), deadline); IERC20(WETH).safeTransfer(beneficiary, exitETH); } /** * Since all Sushi LP held by this contract are auto deposited in Sushi MasterChef, SUSHI rewards accrue. * This allows the governance (the vault working with this contract) to claim the rewards so they can * be sold by governance and compounded back inside via compoundProfits. */ function claimRewards() external nonReentrant onlyGovernance { _poolClaimRewards(); uint256 amount = IERC20(REWARD).balanceOf(address(this)); IERC20(REWARD).safeTransfer(msg.sender, amount); emit ClaimRewards(msg.sender, amount); } /** * SUSHI rewards that were claimed by governance (the vault working with this contract) and sold by * governance can be compounded back inside via this function. Receives all sold rewards as ETH. * Argument capitalProviderRewardPercentmil is the split of the profits that should be given to the * provider of USDC. Use 50000 to have an even 50/50 split of the reward profits. Use 20000 to take 80% * to the ETH providers and leave 20% of reward profits to the USDC provider. */ function compoundProfits(uint256 amountETH, uint256 capitalProviderRewardPercentmil) external nonReentrant onlyGovernance returns ( uint256 pairedUSDC, uint256 pairedETH, uint256 liquidity ) { IERC20(WETH).safeTransferFrom(msg.sender, address(this), amountETH); if (capitalProviderRewardPercentmil > 0) { uint256 ownerETH = amountETH.mul(capitalProviderRewardPercentmil).div(100_000); _poolSwapExactETHForUSDC(ownerETH); amountETH = amountETH.sub(ownerETH); } amountETH = amountETH.div(2); _poolSwapExactETHForUSDC(amountETH); (pairedUSDC, pairedETH, liquidity) = _poolAddLiquidityAndStake(amountETH, block.timestamp); // solhint-disable-line not-rely-on-time totalPairedUSDC = totalPairedUSDC.add(pairedUSDC); totalPairedETH = totalPairedETH.add(pairedETH); totalLiquidity = totalLiquidity.add(liquidity); // not adding to shares to distribute rewards to all shareholders emit CompoundProfits(msg.sender, liquidity); } function _deposit( address beneficiary, uint256 amountETH, uint256 deadline ) private { Minter storage minter = minters[beneficiary]; uint256 shares = _pair(beneficiary, minter, amountETH, deadline); _mint(beneficiary, shares); emit Mint(msg.sender, beneficiary, shares); } /** * Pair deposited ETH with USDC available in the contract's balance to create Sushi LP. */ function _pair( address minterAddress, Minter storage minter, uint256 amountETH, uint256 deadline ) private returns (uint256 shares) { (uint256 pairedUSDC, uint256 pairedETH, uint256 liquidity) = _poolAddLiquidityAndStake(amountETH, deadline); if (totalPairedShares == 0) { shares = liquidity; } else { shares = liquidity.mul(totalPairedShares).div(totalLiquidity); } minter.pairedUSDC = minter.pairedUSDC.add(pairedUSDC); minter.pairedETH = minter.pairedETH.add(pairedETH); minter.pairedShares = minter.pairedShares.add(shares); totalPairedUSDC = totalPairedUSDC.add(pairedUSDC); totalPairedETH = totalPairedETH.add(pairedETH); totalPairedShares = totalPairedShares.add(shares); totalLiquidity = totalLiquidity.add(liquidity); emit Pair(msg.sender, minterAddress, pairedUSDC, pairedETH, liquidity); } function _withdraw( address sender, address beneficiary, uint256 shares, uint256 deadline ) private returns (uint256 exitETH) { Minter storage minter = minters[sender]; shares = Math.min(shares, minter.pairedShares.add(minter.unpairedShares)); require(shares > 0, "sender not in minters"); if (shares > minter.unpairedShares) { _unpair(sender, minter, shares.sub(minter.unpairedShares), deadline); } exitETH = shares.mul(minter.unpairedETH).div(minter.unpairedShares); minter.unpairedETH = minter.unpairedETH.sub(exitETH); minter.unpairedShares = minter.unpairedShares.sub(shares); _burn(sender, shares); emit Burn(sender, beneficiary, shares); } /** * Unpair ETH from USDC by burning Sushi LP and rebalancing IL between the two. */ function _unpair( address minterAddress, Minter storage minter, uint256 shares, uint256 deadline ) private { uint256 liquidity = shares.mul(totalLiquidity).div(totalPairedShares); (uint256 removedETH, uint256 removedUSDC) = _poolUnstakeAndRemoveLiquidity(liquidity, deadline); uint256 pairedUSDC = minter.pairedUSDC.mul(shares).div(minter.pairedShares); uint256 pairedETH = minter.pairedETH.mul(shares).div(minter.pairedShares); (uint256 exitUSDC, uint256 exitETH) = applyRebalance(removedUSDC, removedETH, pairedUSDC, pairedETH); minter.pairedUSDC = minter.pairedUSDC.sub(pairedUSDC); minter.pairedETH = minter.pairedETH.sub(pairedETH); minter.pairedShares = minter.pairedShares.sub(shares); minter.unpairedETH = minter.unpairedETH.add(exitETH); minter.unpairedShares = minter.unpairedShares.add(shares); totalPairedUSDC = totalPairedUSDC.sub(pairedUSDC); totalPairedETH = totalPairedETH.sub(pairedETH); totalPairedShares = totalPairedShares.sub(shares); totalLiquidity = totalLiquidity.sub(liquidity); emit Unpair(msg.sender, minterAddress, exitUSDC, exitETH, liquidity); } /** * Allows the owner (the capital provider of USDC) to emergency exit all of their USDC. * When called, all Sushi LP is burned to extract ETH+USDC, the USDC part is returned to owner. * The ETH will wait in the contract until the original ETH depositors will remove it. */ function emergencyExit(address[] memory minterAddresses) external onlyOwner { for (uint256 i = 0; i < minterAddresses.length; i++) { address minterAddress = minterAddresses[i]; Minter storage minter = minters[minterAddress]; uint256 shares = minter.pairedShares; if (shares > 0) { _unpair(minterAddress, minter, shares, block.timestamp); //solhint-disable-line not-rely-on-time } } withdrawFreeCapital(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./base/SushiswapIntegration.sol"; contract RebalancingStrategy1 is SushiswapIntegration { using SafeMath for uint256; using SafeERC20 for IERC20; /** * Rebalance usd and eth such that the eth provider takes all IL risk but receives all excess eth, * while usd provider's principal is protected */ function applyRebalance( uint256 removedUSDC, uint256 removedETH, uint256 entryUSDC, uint256 entryETH // solhint-disable-line no-unused-vars ) internal returns (uint256 exitUSDC, uint256 exitETH) { if (removedUSDC > entryUSDC) { uint256 deltaUSDC = removedUSDC.sub(entryUSDC); exitETH = removedETH.add(_poolSwapExactUSDCForETH(deltaUSDC)); exitUSDC = entryUSDC; } else { uint256 deltaUSDC = entryUSDC.sub(removedUSDC); uint256 deltaETH = Math.min(removedETH, amountInETHForRequestedOutUSDC(deltaUSDC)); exitUSDC = removedUSDC.add(_poolSwapExactETHForUSDC(deltaETH)); exitETH = removedETH.sub(deltaETH); } } } // 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)); } } // 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: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./LiquidityNexusBase.sol"; import "../interface/ISushiswapRouter.sol"; import "../interface/ISushiMasterChef.sol"; contract SushiswapIntegration is LiquidityNexusBase { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant SLP = address(0x397FF1542f962076d0BFE58eA045FfA2d347ACa0); // Sushiswap USDC/ETH pair address public constant ROUTER = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushiswap Router2 address public constant MASTERCHEF = address(0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd); address public constant REWARD = address(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); uint256 public constant POOL_ID = 1; address[] public pathToETH = new address[](2); address[] public pathToUSDC = new address[](2); constructor() { pathToUSDC[0] = WETH; pathToUSDC[1] = USDC; pathToETH[0] = USDC; pathToETH[1] = WETH; IERC20(USDC).approve(ROUTER, uint256(~0)); IERC20(WETH).approve(ROUTER, uint256(~0)); IERC20(SLP).approve(ROUTER, uint256(~0)); IERC20(SLP).approve(MASTERCHEF, uint256(~0)); } /** * returns price of ETH in USDC */ function quote(uint256 inETH) public view returns (uint256 outUSDC) { (uint112 rUSDC, uint112 rETH, ) = IUniswapV2Pair(SLP).getReserves(); outUSDC = IUniswapV2Router02(ROUTER).quote(inETH, rETH, rUSDC); } /** * returns price of USDC in ETH */ function quoteInverse(uint256 inUSDC) public view returns (uint256 outETH) { (uint112 rUSDC, uint112 rETH, ) = IUniswapV2Pair(SLP).getReserves(); outETH = IUniswapV2Router02(ROUTER).quote(inUSDC, rUSDC, rETH); } /** * returns ETH amount (in) needed when swapping for requested USDC amount (out) */ function amountInETHForRequestedOutUSDC(uint256 outUSDC) public view returns (uint256 inETH) { inETH = IUniswapV2Router02(ROUTER).getAmountsIn(outUSDC, pathToUSDC)[0]; } function _poolSwapExactUSDCForETH(uint256 inUSDC) internal returns (uint256 outETH) { if (inUSDC == 0) return 0; uint256[] memory amounts = IUniswapV2Router02(ROUTER).swapExactTokensForTokens(inUSDC, 0, pathToETH, address(this), block.timestamp); // solhint-disable-line not-rely-on-time require(inUSDC == amounts[0], "leftover USDC"); outETH = amounts[1]; } function _poolSwapExactETHForUSDC(uint256 inETH) internal returns (uint256 outUSDC) { if (inETH == 0) return 0; uint256[] memory amounts = IUniswapV2Router02(ROUTER).swapExactTokensForTokens( inETH, 0, pathToUSDC, address(this), block.timestamp // solhint-disable-line not-rely-on-time ); require(inETH == amounts[0], "leftover ETH"); outUSDC = amounts[1]; } function _poolAddLiquidityAndStake(uint256 amountETH, uint256 deadline) internal returns ( uint256 addedUSDC, uint256 addedETH, uint256 liquidity ) { require(IERC20(WETH).balanceOf(address(this)) >= amountETH, "not enough WETH"); uint256 quotedUSDC = quote(amountETH); require(IERC20(USDC).balanceOf(address(this)) >= quotedUSDC, "not enough free capital"); (addedETH, addedUSDC, liquidity) = IUniswapV2Router02(ROUTER).addLiquidity( WETH, USDC, amountETH, quotedUSDC, amountETH, 0, address(this), deadline ); require(addedETH == amountETH, "leftover ETH"); IMasterChef(MASTERCHEF).deposit(POOL_ID, liquidity); } function _poolUnstakeAndRemoveLiquidity(uint256 liquidity, uint256 deadline) internal returns (uint256 removedETH, uint256 removedUSDC) { if (liquidity == 0) return (0, 0); IMasterChef(MASTERCHEF).withdraw(POOL_ID, liquidity); (removedETH, removedUSDC) = IUniswapV2Router02(ROUTER).removeLiquidity( WETH, USDC, liquidity, 0, 0, address(this), deadline ); } function _poolClaimRewards() internal { IMasterChef(MASTERCHEF).deposit(POOL_ID, 0); } function isSalvagable(address token) internal override returns (bool) { return super.isSalvagable(token) && token != SLP && token != REWARD; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; contract LiquidityNexusBase is Ownable, Pausable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); address public governance; constructor() { governance = msg.sender; } modifier onlyGovernance() { require(msg.sender == governance, "only governance"); _; } function setGovernance(address _governance) external onlyGovernance { require(_governance != address(0), "null governance"); governance = _governance; } /** * Only the owner is supposed to deposit USDC into this contract. */ function depositCapital(uint256 amount) public onlyOwner { if (amount > 0) { IERC20(USDC).safeTransferFrom(msg.sender, address(this), amount); } } function depositAllCapital() external onlyOwner { depositCapital(IERC20(USDC).balanceOf(msg.sender)); } /** * The owner can withdraw the unused USDC capital that they had deposited earlier. */ function withdrawFreeCapital() public onlyOwner { uint256 balance = IERC20(USDC).balanceOf(address(this)); if (balance > 0) { IERC20(USDC).safeTransfer(msg.sender, balance); } } /** * Pause will only prevent new ETH deposits (addLiquidity). Existing depositors will still * be able to removeLiquidity even when paused. */ function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } /** * Owner can only salvage unrelated tokens that were sent by mistake. */ function salvage(address[] memory tokens_) external onlyOwner { for (uint256 i = 0; i < tokens_.length; i++) { address token = tokens_[i]; require(isSalvagable(token), "not salvagable"); uint256 balance = IERC20(token).balanceOf(address(this)); if (balance > 0) { IERC20(token).safeTransfer(msg.sender, balance); } } } function isSalvagable(address token) internal virtual returns (bool) { return token != WETH && token != USDC; } receive() external payable {} // solhint-disable-line no-empty-blocks } // SPDX-License-Identifier: MIT // solhint-disable pragma solidity ^0.7.6; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 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 (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); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } interface IERC20Uniswap { 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); } interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IMasterChef { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; function userInfo(uint256 _pid, address _user) external view returns (uint256 amount, uint256 rewardDebt); function poolInfo(uint256 _pid) external view returns ( address lpToken, uint256, uint256, uint256 ); function massUpdatePools() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } }
The owner can withdraw the unused USDC capital that they had deposited earlier./
function withdrawFreeCapital() public onlyOwner { uint256 balance = IERC20(USDC).balanceOf(address(this)); if (balance > 0) { IERC20(USDC).safeTransfer(msg.sender, balance); } }
6,891,493
pragma solidity ^0.5.0; contract Jukebox { // --- Contract properties ------------------------------------------------ // // --- Data structures --- // // Song type struct Song { uint id; uint durationSecs; } // Queued song type struct QueuedSong { Song song; // The song type uint timestampSecs; // Unix timestamp when it was queued. } // --- State --- // // Song state Song[3] songsAvailable; // Songs currently queued QueuedSong[5] queue; uint queueSize = 0; // --- Events --- // event SongSkip(uint skippedSongId); event SongPrepend(uint songId); event SongAppend(uint songId); // --- Constructor -------------------------------------------------------- // constructor() public { songsAvailable[0] = Song(0, 120); songsAvailable[1] = Song(1, 120); songsAvailable[2] = Song(2, 120); } // --- Business logic ----------------------------------------------------- // // --- Getters --- // /** Get the current size of the song queue. */ function getQueueSize() public view returns (uint) { return queueSize; } /** Return data about a song currently in the queue. */ function getSongDataByQueueIndex(uint queueIndex) public view returns (uint songId, uint durationSecs, uint timestampSecs, bool isSongCompleted) { require(queueIndex < queueSize - 1, "Song queue is smaller than the provided index."); QueuedSong memory qsong = queue[queueIndex]; // Extract data from state songId = qsong.song.id; durationSecs = qsong.song.durationSecs; timestampSecs = qsong.timestampSecs; isSongCompleted = block.timestamp >= timestampSecs + durationSecs; return (songId, durationSecs, timestampSecs, isSongCompleted); } /** Return data about a song from its unique ID. */ function getSongDataBySongId(uint songId) public view returns (uint id, uint durationSecs) { for (uint i = 0; i < songsAvailable.length; i++) { Song memory song = songsAvailable[i]; if (song.id == songId) { id = song.id; durationSecs = song.durationSecs; return (id, durationSecs); } } require(false, "Song data not found."); } /** * Get the queue index of the currently playing song. */ function getCurrentSongQueueIndex() public view returns (uint songQueueIndex) { for (uint i = 0; i < queueSize; i++) { QueuedSong memory qsong = queue[i]; if (block.timestamp >= qsong.timestampSecs + qsong.song.durationSecs) { return i; } } require(false, "No song is currently playing."); } // --- State updates --- // /** Prepend a song to the jukebox playlist. */ function prependSongToQueue(uint songId) public payable {} /** Append a song to the jukebox playlist. */ function appendSongToQueue(uint songId) public payable {} /** Skip the currently playing song. */ function skipSong() public {} /** Remove currently playing song from the queue. */ function reconcileSongQueue() private {} }
Get the current size of the song queue. /
function getQueueSize() public view returns (uint) { return queueSize; }
5,370,020
./partial_match/42/0xdFf18ab57909a57e4660435B0935C09A1407d29A/sources/MasterchefDelegator.sol
Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public { require(minters[msg.sender] == true, "NTS : You are not the miner"); _mint(_to, _amount); }
3,296,217
pragma solidity ^0.4.24; /** * @title Ownable * @dev El contrato de propiedad tiene una dirección de propietario y proporciona un control de autorización básico * funciones, esto simplifica la implementación de "permisos de usuario". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev El constructor Ownable establece el "propietario" original del contrato al remitente * cuenta. */ constructor() public { owner = msg.sender; } /** * @dev Lanza si es llamado por cualquier cuenta que no sea el propietario. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Permite al propietario actual transferir el control del contrato a un nuevo propietario. * @param newOwner La dirección a la que se transfiere la propiedad. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Permite al propietario actual ceder el control del contrato. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title SafeMath * @dev Operaciones matemáticas con controles de seguridad que arrojan por error. */ library SafeMath { /** * @dev Multiplica dos números, lanza en desbordamiento. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev División entera de dos números, truncando el cociente. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Resta dos números, arroja en desbordamiento (es decir, si el sustraendo es mayor que el minuendo). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Agrega dos números, arroja sobre desbordamiento. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Versión más sencilla de la interfaz ERC20 * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementación del token estándar básico. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * 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(balances[msg.sender] >= _value); // Check if the sender has enough balances[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(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply_ -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Funciónpara acuñar fichas * @param _to La dirección que recibirá las fichas acuñadas. * @param _amount La cantidad de fichas para acuñar. * @return Un valor booleano que indica si la operación se realizó correctamente. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Función para dejar de acuñar nuevas fichas. * @return Es cierto si la operación fue exitosa. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract Coinbase is Ownable { using SafeMath for uint256; uint256 public blockHeight; uint256 public decimals; uint256 public coinbaseInit; // Generar nuevo bloque cada 6 horas. Reducir a la mitad la base de monedas cada 120 días. uint256 public halvingPeriod = 4 * 120; uint256 public maxSupply; uint256[6] private coinbaseArray; uint256 public exodus; event LogBlockHeight(uint256 blockHeight); constructor(uint256 _decimals) public{ decimals = _decimals; maxSupply = 710000000 * (10 ** uint256(decimals)); // 10% of maxSupply acuñar antes de bloque de genesis exodus = maxSupply / 10; // 90% de maxSupply para los próximos 2 años. coinbaseInit = 196875 * (10 ** uint256(decimals)); coinbaseArray = [ coinbaseInit, coinbaseInit / 2, coinbaseInit / 4, coinbaseInit / 8, coinbaseInit / 16, coinbaseInit / 16 ]; } /** * @dev Función para aumentar la altura del bloque. * @return */ function nextBlock() onlyOwner public { blockHeight = blockHeight.add(1); emit LogBlockHeight(blockHeight); } /** * @dev Función para calcular la cantidad de coinbase del bloque en este momento. * @return Un booleano que indica si la operación se realizó correctamente. */ function coinbaseAmount() view internal returns (uint){ uint256 index = blockHeight.sub(1).div(halvingPeriod); if (index > 5 || index < 0) { return 0; } return coinbaseArray[index]; } } contract SlonpayToken is MintableToken, PausableToken, Coinbase { string public constant name = "Slonpay Token"; string public constant symbol = "SLPT"; uint256 public constant decimals = 18; constructor() Coinbase(decimals) public{ mint(owner, exodus); } /** * @dev Función para coinbase en nuevo bloque * @return Un booleano que indica si la operación se realizó correctamente. */ function coinbase() onlyOwner canMint whenNotPaused public returns (bool) { nextBlock(); uint256 _amount = coinbaseAmount(); if (_amount == 0) { finishMinting(); return false; } return super.mint(owner, _amount); } /** * @dev Función para dejar de acuñar nuevas fichas. * @return Es cierto si la operación fue exitosa. */ function finishMinting() onlyOwner canMint whenNotPaused public returns (bool) { return super.finishMinting(); } /** * @dev Permite al propietario actual transferir el control del contrato a un nuevo propietario. * @param newOwner La dirección para transferir la propiedad a. */ function transferOwnership(address newOwner) onlyOwner whenNotPaused public { super.transferOwnership(newOwner); } /** * The fallback function. */ function() payable public { revert(); } }
Función para calcular la cantidad de coinbase del bloque en este momento. return Un booleano que indica si la operación se realizó correctamente./
function coinbaseAmount() view internal returns (uint){ uint256 index = blockHeight.sub(1).div(halvingPeriod); if (index > 5 || index < 0) { return 0; } return coinbaseArray[index]; }
898,019
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/ICumulativeMerkleDrop.sol"; contract CumulativeMerkleDrop is Ownable, ICumulativeMerkleDrop { using SafeERC20 for IERC20; using MerkleProof for bytes32[]; address public immutable override token; address public rewardsHolder; bytes32 public override merkleRoot; mapping(address => uint256) public cumulativeClaimed; struct Claim { address account; uint256 amount; bytes32[] proof; } event RewardsHolderUpdated(address oldRewardsHolder, address newRewardsHolder); constructor(address token_, address rewardsHolder_) { require(IERC20(token_).totalSupply() > 0, "Token contract must be set"); require(rewardsHolder_ != address(0), "Rewards GHolder must be an address"); token = token_; rewardsHolder = rewardsHolder_; } function setMerkleRoot(bytes32 merkleRoot_) external override onlyOwner { emit MerkelRootUpdated(merkleRoot, merkleRoot_); merkleRoot = merkleRoot_; } function setRewardsHolder(address rewardsHolder_) external onlyOwner { require(rewardsHolder_ != address(0)); emit RewardsHolderUpdated(rewardsHolder, rewardsHolder_); rewardsHolder = rewardsHolder_; } function claim( address account, uint256 cumulativeAmount, bytes32 expectedMerkleRoot, bytes32[] calldata merkleProof ) public override { require(merkleRoot == expectedMerkleRoot, "CMD: Merkle root was updated"); // Verify the merkle proof bytes32 leaf = keccak256(abi.encodePacked(account, cumulativeAmount)); require(_verifyAsm(merkleProof, expectedMerkleRoot, leaf), "CMD: Invalid proof"); // Mark it claimed uint256 preclaimed = cumulativeClaimed[account]; require(preclaimed < cumulativeAmount, "CMD: Nothing to claim"); cumulativeClaimed[account] = cumulativeAmount; // Send the token unchecked { uint256 amount = cumulativeAmount - preclaimed; IERC20(token).safeTransferFrom(rewardsHolder, account, amount); emit Claimed(account, amount); } } function batchClaim( bytes32 expectedMerkleRoot, Claim[] calldata Claims ) external { for (uint i; i < Claims.length; i++) { claim( Claims[i].account, Claims[i].amount, expectedMerkleRoot, Claims[i].proof ); } } function verify(bytes32[] calldata merkleProof, bytes32 root, bytes32 leaf) public pure returns (bool) { return merkleProof.verify(root, leaf); } function _verifyAsm(bytes32[] calldata proof, bytes32 root, bytes32 leaf) private pure returns (bool valid) { // solhint-disable-next-line no-inline-assembly assembly { let mem1 := mload(0x40) let mem2 := add(mem1, 0x20) let ptr := proof.offset for { let end := add(ptr, mul(0x20, proof.length)) } lt(ptr, end) { ptr := add(ptr, 0x20) } { let node := calldataload(ptr) switch lt(leaf, node) case 1 { mstore(mem1, leaf) mstore(mem2, node) } default { mstore(mem1, node) mstore(mem2, leaf) } leaf := keccak256(mem1, 0x40) } valid := eq(root, leaf) } } }
Verify the merkle proof Mark it claimed Send the token
function claim( address account, uint256 cumulativeAmount, bytes32 expectedMerkleRoot, bytes32[] calldata merkleProof ) public override { require(merkleRoot == expectedMerkleRoot, "CMD: Merkle root was updated"); bytes32 leaf = keccak256(abi.encodePacked(account, cumulativeAmount)); require(_verifyAsm(merkleProof, expectedMerkleRoot, leaf), "CMD: Invalid proof"); uint256 preclaimed = cumulativeClaimed[account]; require(preclaimed < cumulativeAmount, "CMD: Nothing to claim"); cumulativeClaimed[account] = cumulativeAmount; unchecked { uint256 amount = cumulativeAmount - preclaimed; IERC20(token).safeTransferFrom(rewardsHolder, account, amount); emit Claimed(account, amount); } }
15,795,472
./partial_match/1/0xd12917F42E09e216623010EB5f15c39d4978d322/sources/Arb2EthTarget.sol
The condition for slash is that the transfer has timed out Meanwhile we need to request a slash transaction to the source chain to withdraw the LnProvider's margin On the source chain, we need to verify all the transfers before has been relayed or slashed. So we needs to carry the the previous shash transferId to ensure that the slash is continuous. slasher = msg.sender Do not slash `transferId` in source chain unless `latestSlashTransferId` has been slashed
function _slashAndRemoteRefund( TransferParameter calldata params, bytes32 expectedTransferId ) internal returns(bytes memory message) { require(block.timestamp > params.timestamp + MIN_REFUND_TIMESTAMP, "slash time not expired"); _fillTransfer(params, expectedTransferId); slashInfos[expectedTransferId] = SlashInfo(params.provider, params.sourceToken, msg.sender); message = _encodeSlashCall( fillTransfers[expectedTransferId], expectedTransferId, params.provider, params.sourceToken, msg.sender ); emit TransferFilled(expectedTransferId, msg.sender); }
4,118,729
pragma solidity ^0.5.3; contract Identity { enum VerifyStatus {none, pending, verified, rejected} struct PersonalData { string name; string located; string privData; string shareKey; uint dob; VerifyStatus status; } struct VerifierData { string pubKey; uint task; } mapping (address => PersonalData) internal userInfo; mapping (address => bool) internal isVerifyRight; mapping (address => VerifierData) internal verifierInfo; mapping (address => address[]) internal verifier2users; address internal owner; address[] internal verifiers; /* -- Constructor -- */ // /// @notice Constructor to create a Identity contract /// @dev Owner is runner of this contract constructor() public { owner = msg.sender; } modifier onlyOwner() { require( msg.sender == owner, "Only owner" ); _; } modifier onlyVerifier() { require( isVerifyRight[msg.sender] == true, "Only verifier"); _; } /// @notice This function for user can register a identity /// @param name is full name of user /// @param located is located address of user /// @param dob is date of birth of user /// @param data is private data as hash of data that was store on IPFS /// @param shareKey is secret key of user was encrypted /// @param verifier is address of verifier function registerIdentity( string calldata name, string calldata located, uint dob, string calldata data, string calldata shareKey, address verifier) external { require( bytes(name).length > 3, "Your name is must be greater 3 characters" ); require( bytes(located).length > 10, "Your located address must be greater 10 characters" ); require( dob < now && dob > 0, "Date of birth is wrong" ); require( userInfo[msg.sender].dob == 0, "You have already registered info" ); require( isVerifyRight[verifier] == true, "Address verifier is incorrect"); require( verifierInfo[verifier].task <= 10, "The verifier that you selected is no longer available" ); userInfo[msg.sender] = PersonalData( name, located, data, shareKey, dob, VerifyStatus.pending ); // PersonalData memory temp; // temp.name = name; // temp.located = located; // temp.dob = dob; // temp.privData = data; // temp.shareKey = shareKey; // temp.status = VerifyStatus.pending; // userInfo[msg.sender] = temp; verifier2users[verifier].push(msg.sender); verifierInfo[verifier].task += 1; } /// @notice Get information of an user /// @param user is address of user /// @return Name, Located Address, Date of birth and verify status function getIdentity(address user) external view returns ( string memory name, string memory located, uint dob, string memory privData, string memory shareKey, VerifyStatus status ) { name = userInfo[user].name; located = userInfo[user].located; dob = userInfo[user].dob; status = userInfo[user].status; privData = userInfo[user].privData; shareKey = userInfo[user].shareKey; } /// @notice This function for verifier to verify an identity /// @param user is address of user /// @param status is status include `true` is verified and `false` is rejected function verify(address user, bool status) external onlyVerifier() { require( userInfo[user].status == VerifyStatus.pending, "User that you verifiy must be have data" ); uint loopLimit = verifier2users[msg.sender].length; bool isVerifier2User = false; for (uint i = 0; i < loopLimit; i++) { if (verifier2users[msg.sender][i] == user) { isVerifier2User = true; } } require( isVerifier2User == true, "User must be requested verifier" ); userInfo[user].status = status ? VerifyStatus.verified : VerifyStatus.rejected; verifierInfo[msg.sender].task -= 1; } /// @notice Get status of identity /// @param user is address of user /// @return Status (1 => pending, 2 => verified, 3 => rejected) function getStatus(address user) external view returns(VerifyStatus) { return userInfo[user].status; } /// @notice This function for owner to add a verifier /// @param verifier is address of verifier /// @param pubKey is public key of verifier function addVerifier(address verifier, string calldata pubKey) external onlyOwner() { require( isVerifyRight[verifier] == false, "This address have already added" ); verifierInfo[verifier] = VerifierData(pubKey, 0); verifiers.push(verifier); isVerifyRight[verifier] = true; } /// @notice Get list all verifiers /// @return array of verifier's addresses and count function getVerifierAddresses() external view returns (address[] memory) { return verifiers; } /// @notice Get information of a verifier /// @param verifier is address of verifier /// @return Public key and number task of verifier function getVerifier(address verifier) external view returns(string memory pubKey, uint task) { pubKey = verifierInfo[verifier].pubKey; task = verifierInfo[verifier].task; } /// @notice Check identity of an address is verified /// @param user is address of user /// @return `true` if identity of address is verified function isVerified(address user) external view returns(bool) { return userInfo[user].status == VerifyStatus.verified; } /// @notice Get list user that requested by Verifier /// @return List of users function getUsersRequested() external onlyVerifier() view returns(address[] memory) { return verifier2users[msg.sender]; } /// @notice Function is used for other contract /// @param verifier is address of user that you want to check /// @return `true` if address is verifier function isVerifier(address verifier) external view returns(bool) { return isVerifyRight[verifier]; } /// @notice Change public key of verifier /// @param verifier is address of verifier /// @param newPubKey is new public key function changePubKey (address verifier, string calldata newPubKey) external onlyOwner { verifierInfo[verifier].pubKey = newPubKey; } /// @notice Function is used to check if owner /// @return `true` if sender is owner of contract function isOwner() external view returns(bool) { return msg.sender == owner; } }
Get status of identity user is address of user return Status (1 => pending, 2 => verified, 3 => rejected)
function getStatus(address user) external view returns(VerifyStatus) { return userInfo[user].status; }
12,759,793
./full_match/5/0x24F699a57a1312508ae420b4a664139C78D63A3c/sources/project_/contracts/SweetToken.sol
Burn remaining locked tokens of the sender only if there are locked tokens
function _transfer(address sender, address recipient, uint256 amount) internal virtual override { require(isTradable || sender == owner(), "Transfers are not allowed at the moment"); require(balanceOf(sender) - _locked[sender].amount >= amount, "Not enough unlocked tokens"); _updateLocked(sender); super._transfer(sender, recipient, amount); if (sender == uniswapPair && recipient != owner() && msg.sender == sender && recipient != uniswapPair && recipient != uniswapRouter) { uint256 lockedAmount = amount * 9 / 10; _lockTokens(recipient, lockedAmount); } if (sender != uniswapPair && sender != uniswapRouter) { uint256 remainingLocked = _locked[sender].amount; if (remainingLocked > 0) { _burn(sender, remainingLocked); _locked[sender].amount = 0; } } }
1,931,956
pragma solidity >=0.4.21 <0.6.0; pragma experimental ABIEncoderV2; import "./provableAPI_0.5.sol"; contract Access is usingProvable { address public owner; bytes32 noID = 0; event IDK(bytes32 id); event HOPE(Member mem); event LogNewProvableQuery(string description); event Balance(uint amount, uint moneyNeeded); event QueryRes(string result); uint public last_completed_migration; uint public balance; struct Modification { string timeStamp; string modType; } struct Member { bytes32 id; string name; bool proxyUser; uint256[] mods; uint256[] mTime; } struct Researcher { bytes32 id; string name; uint256[] mods; uint256[] mTime; } string res; mapping(uint256=>string) modMap; mapping(bytes32=>Member) memMap; mapping(bytes32=>Researcher) rMap; mapping(string=>bool) memName; mapping(string=>bool) rName; Member[] memList; Researcher[] rList; constructor() public { owner = msg.sender; modMap[0] = "POST"; modMap[1] = "PUT"; modMap[2] = "GET"; modMap[3] = "DELETE"; addMember("ken", false); addResearcher("Danny"); } function __callback(bytes32 myid, string memory result) public { if (msg.sender != provable_cbAddress()) revert("Not Enough Funds"); res = result; emit QueryRes(res); } function() payable external {} modifier isOwner() { if (msg.sender == owner) _; } function getAccess() public view { require(msg.sender == owner, "Access not Granted!"); } function memberAccess(string memory _name) public view { require(memName[_name], "Member does not exist!"); } function researcherAccess(string memory _name) public view { require(rName[_name], "Researcher does not exist!"); } function addMember( string memory _name, bool _proxy) public isOwner { bytes32 lunaID = keccak256(abi.encodePacked(_name, _proxy)); uint256[] memory mods; Member memory newMember = Member(lunaID, _name, _proxy, mods, mods); memMap[lunaID] = newMember; memName[_name] = true; memList.push(newMember); } function addResearcher( string memory _name) public isOwner { bytes32 lunaID = keccak256(abi.encodePacked(_name)); uint256[] memory mods; Researcher memory newResearcher = Researcher(lunaID, _name, mods, mods); rMap[lunaID] = newResearcher; rName[_name] = true; rList.push(newResearcher); } function queryDB() public payable { //emit Balance(address(this).balance, provable_getPrice("URL")); if (provable_getPrice("URL") > address(this).balance) { emit LogNewProvableQuery("Provable query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogNewProvableQuery("Provable query was sent, standing by for the answer.."); provable_query("URL", "json(https://purple-elephant-56.localtunnel.me/1/Danny).name"); } } function help(uint256 _index) public { emit IDK(memList[_index].id); emit HOPE(memList[_index]); } function getRes() public pure returns (string memory res) { return res; } }
emit Balance(address(this).balance, provable_getPrice("URL"));
function queryDB() public payable { if (provable_getPrice("URL") > address(this).balance) { emit LogNewProvableQuery("Provable query was NOT sent, please add some ETH to cover for the query fee"); emit LogNewProvableQuery("Provable query was sent, standing by for the answer.."); } }
5,376,814
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/AggregatorV3Interface.sol"; import "../interface/IDefxNFTFactory.sol"; import '../interface/ITokenBonusSharePool.sol'; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract BnbPriceUSDTPrediction is Ownable, Pausable,Initializable { using SafeMath for uint256; // enum Position {Bull, Bear} //期权周期 struct Round { uint256 epoch; //index uint256 startBlock; //开始区块 uint256 lockBlock; //锁的区块 uint256 endBlock; //结算区块 int256 lockPrice; //锁定价格 int256 closePrice; //结算价格 uint256 totalAmount; //投注总金额 uint256 bullAmount; //看涨金额 uint256 bearAmount; //看跌金额 uint256 rewardBaseCalAmount; //赢家投注金额 uint256 rewardAmount; //赢家金额 bool oracleCalled; //是否已经获取价格 } //赌注即订单 struct BetInfo { Position position; //看涨或者看跌 uint256 amount; //金额 bool claimed; // 是否需要领取 uint256 nftTokenId; } bool public genesisStartOnce = false; //是否调用初始化开始方法 bool public genesisLockOnce = false; //是否调用初始化锁定方法 uint256 public currentEpoch; //当前周期角标 uint256 public intervalBlocks; //100 uint256 public bufferBlocks; //15 address public adminAddress; //管理员地址 address public operatorAddress; //操作员地址 uint256 public oracleLatestRoundId; uint256 public TOTAL_RATE; // 100% uint256 public rewardRate; // 90% 赢家比率 uint256 public treasuryRate; // 10% 合约维护者佣金比率 uint256 public minBetAmount; //最小投资金额 uint256 public oracleUpdateAllowance; // seconds 允许价格相差的时间 mapping(uint256 => Round) public rounds; //期权周期mapping, currentEpoch mapping(uint256 => mapping(address => BetInfo)) public ledger; //期权周期=>用户下注详细 mapping(address => uint256[]) public userRounds; // IDefxNFTFactory public nftTokenFactory; AggregatorV3Interface internal oracle; //预言机 ITokenBonusSharePool public bonusSharePool; //分红 IERC20 public betToken; event StartRound(uint256 indexed epoch, uint256 blockNumber, uint256 intervalBlocks); event LockRound(uint256 indexed epoch, uint256 blockNumber, int256 price); event EndRound(uint256 indexed epoch, uint256 blockNumber, int256 price); event BetBull(address indexed sender, uint256 indexed currentEpoch, uint256 amount, uint256 nftTokenId); event BetBear(address indexed sender, uint256 indexed currentEpoch, uint256 amount, uint256 nftTokenId); event Claim(address indexed sender, uint256 indexed currentEpoch, uint256 amount, uint256 nftTokenId); event RatesUpdated(uint256 indexed epoch, uint256 rewardRate, uint256 treasuryRate); event MinBetAmountUpdated(uint256 indexed epoch, uint256 minBetAmount); event RewardsCalculated(uint256 indexed epoch, uint256 rewardBaseCalAmount, uint256 rewardAmount, uint256 treasuryAmount); event Pause(uint256 epoch); event Unpause(uint256 epoch); modifier onlyAdmin() { require(msg.sender == adminAddress, "admin: wut?"); _; } modifier onlyOperator() { require(msg.sender == operatorAddress, "operator: wut?"); _; } modifier onlyAdminOrOperator() { require(msg.sender == adminAddress || msg.sender == operatorAddress, "admin | operator: wut?"); _; } modifier notContract() { require(!_isContract(msg.sender), "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); _; } function initialize( address _betToken, AggregatorV3Interface _oracle, address _adminAddress, address _operatorAddress, uint256 _intervalBlocks, uint256 _bufferBlocks, uint256 _minBetAmount, uint256 _TOTAL_RATE, uint256 _rewardRate, uint256 _treasuryRate, uint256 _oracleUpdateAllowance, IDefxNFTFactory _nftTokenFactory) public initializer { oracle = _oracle; betToken = IERC20(_betToken); adminAddress = _adminAddress; operatorAddress = _operatorAddress; intervalBlocks = _intervalBlocks; bufferBlocks = _bufferBlocks; minBetAmount = _minBetAmount; TOTAL_RATE = _TOTAL_RATE; rewardRate = _rewardRate; treasuryRate = _treasuryRate; oracleUpdateAllowance = _oracleUpdateAllowance; nftTokenFactory = _nftTokenFactory; } /** * @dev set admin address * callable by owner */ function setAdmin(address _adminAddress) external onlyAdmin { require(_adminAddress != address(0), "Cannot be zero address"); adminAddress = _adminAddress; } /** * @dev set operator address * callable by admin */ function setOperator(address _operatorAddress) external onlyAdmin { require(_operatorAddress != address(0), "Cannot be zero address"); operatorAddress = _operatorAddress; } /** * @dev set interval blocks * callable by admin */ function setIntervalBlocks(uint256 _intervalBlocks) external onlyAdmin { intervalBlocks = _intervalBlocks; } /** * @dev set buffer blocks * callable by admin */ function setBufferBlocks(uint256 _bufferBlocks) external onlyAdmin { require(_bufferBlocks <= intervalBlocks, "Cannot be more than intervalBlocks"); bufferBlocks = _bufferBlocks; } /** * @dev set Oracle address * callable by admin */ function setOracle(address _oracle) external onlyAdmin { require(_oracle != address(0), "Cannot be zero address"); oracle = AggregatorV3Interface(_oracle); } /** * @dev set oracle update allowance * callable by admin */ function setOracleUpdateAllowance(uint256 _oracleUpdateAllowance) external onlyAdmin { oracleUpdateAllowance = _oracleUpdateAllowance; } /** * @dev set reward rate /设置盈利率 * callable by admin */ function setRewardRate(uint256 _rewardRate) external onlyAdmin whenPaused{ require(_rewardRate <= TOTAL_RATE, "rewardRate cannot be more than 100%"); rewardRate = _rewardRate; treasuryRate = TOTAL_RATE.sub(_rewardRate); emit RatesUpdated(currentEpoch, rewardRate, treasuryRate); } /** * @dev set treasury rate * callable by admin */ function setTreasuryRate(uint256 _treasuryRate) external onlyAdmin { require(_treasuryRate <= TOTAL_RATE, "treasuryRate cannot be more than 100%"); rewardRate = TOTAL_RATE.sub(_treasuryRate); treasuryRate = _treasuryRate; emit RatesUpdated(currentEpoch, rewardRate, treasuryRate); } /** * @dev set minBetAmount * callable by admin */ function setMinBetAmount(uint256 _minBetAmount) external onlyAdmin { minBetAmount = _minBetAmount; emit MinBetAmountUpdated(currentEpoch, minBetAmount); } function setBonusSharePool(address _bonusSharePool) external onlyAdmin{ bonusSharePool = ITokenBonusSharePool(_bonusSharePool); } function setBetToken(address _betToken) external onlyAdmin { betToken = IERC20(_betToken); } /** * @dev Start genesis round/ */ function genesisStartRound() external onlyAdminOrOperator whenNotPaused { require(!genesisStartOnce, "Can only run genesisStartRound once"); currentEpoch = currentEpoch + 1; _startRound(currentEpoch, getRoundStartBlock()); genesisStartOnce = true; } /** * @dev Lock genesis round/ */ function genesisLockRound() external onlyAdminOrOperator whenNotPaused { require(genesisStartOnce, "Can only run after genesisStartRound is triggered"); require(!genesisLockOnce, "Can only run genesisLockRound once"); require( block.number <= rounds[currentEpoch].lockBlock.add(bufferBlocks), "Can only lock round within bufferBlocks" ); int256 currentPrice = _getPriceFromOracle(); _safeLockRound(currentEpoch, currentPrice); currentEpoch = currentEpoch + 1; _startRound(currentEpoch, getRoundStartBlock()); genesisLockOnce = true; } /** * * @dev Start the next round n, lock price for round n-1, end round n-2 */ function executeRound() external onlyAdminOrOperator whenNotPaused { require( genesisStartOnce && genesisLockOnce, "Can only run after genesisStartRound and genesisLockRound is triggered" ); int256 currentPrice = _getPriceFromOracle(); // CurrentEpoch refers to previous round (n-1) _safeLockRound(currentEpoch, currentPrice); _safeEndRound(currentEpoch - 1, currentPrice); _calculateRewards(currentEpoch - 1); // Increment currentEpoch to current round (n) currentEpoch = currentEpoch + 1; _safeStartRound(currentEpoch); if(currentEpoch >= 5 && rounds[currentEpoch - 5].totalAmount == 0) { delete rounds[currentEpoch - 5]; } } /** * @dev Bet bear position */ function betBear(uint256 amount) external payable whenNotPaused notContract { require(_bettable(currentEpoch), "Round not bettable"); require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount"); require(betToken.transferFrom(msg.sender, address(this), amount), "transferFrom error"); require(ledger[currentEpoch][msg.sender].amount == 0, "Can only bet once per round"); // Update round data Round storage round = rounds[currentEpoch]; round.totalAmount = round.totalAmount.add(amount); round.bearAmount = round.bearAmount.add(amount); // Update user data BetInfo storage betInfo = ledger[currentEpoch][msg.sender]; betInfo.position = Position.Bear; betInfo.amount = amount; betInfo.nftTokenId = 0; userRounds[msg.sender].push(currentEpoch); uint256 fee = betInfo.amount.mul(treasuryRate).div(TOTAL_RATE); bonusSharePool.predictionBet(msg.sender, amount, fee); emit BetBear(msg.sender, currentEpoch, amount, betInfo.nftTokenId); } /** * @dev Bet bull position */ function betBull(uint256 amount) external payable whenNotPaused notContract { require(_bettable(currentEpoch), "Round not bettable"); require(amount >= minBetAmount, "Bet amount must be greater than minBetAmount"); require(betToken.transferFrom(msg.sender, address(this), amount), "transferFrom error"); require(ledger[currentEpoch][msg.sender].amount == 0, "Can only bet once per round"); // Update round data Round storage round = rounds[currentEpoch]; round.totalAmount = round.totalAmount.add(amount); round.bullAmount = round.bullAmount.add(amount); // Update user data BetInfo storage betInfo = ledger[currentEpoch][msg.sender]; betInfo.position = Position.Bull; betInfo.amount = amount; betInfo.nftTokenId = 0; userRounds[msg.sender].push(currentEpoch); uint256 fee = betInfo.amount.mul(treasuryRate).div(TOTAL_RATE); bonusSharePool.predictionBet(msg.sender, amount, fee); emit BetBull(msg.sender, currentEpoch, amount, betInfo.nftTokenId); } /** * 结算收益 * @dev Claim reward */ function claim(uint256 epoch) external payable notContract returns(uint256){ require(rounds[epoch].startBlock != 0, "Round has not started"); require(block.number > rounds[epoch].endBlock, "Round has not ended"); require(!ledger[epoch][msg.sender].claimed, "Rewards claimed"); require(ledger[epoch][msg.sender].amount > 0, "not bet"); BetInfo storage betInfo = ledger[epoch][msg.sender]; uint256 reward; uint256 nftToken = 0; // Round valid, claim rewards if (rounds[epoch].oracleCalled) { if(claimable(epoch, msg.sender)) { Round memory round = rounds[epoch]; reward = ledger[epoch][msg.sender].amount.mul(round.rewardAmount).div(round.rewardBaseCalAmount); require(betToken.transfer(msg.sender, reward), "transfer error"); } else { betInfo.nftTokenId = nftTokenFactory.doMint(msg.sender, currentEpoch, betInfo.amount); nftToken = betInfo.nftTokenId; } } // Round invalid, refund bet amount else { require(refundable(epoch, msg.sender), "Not eligible for refund"); reward = ledger[epoch][msg.sender].amount.mul(rewardRate).div(TOTAL_RATE); require(betToken.transfer(msg.sender, reward), "transfer error"); } betInfo.claimed = true; emit Claim(msg.sender, epoch, reward, betInfo.nftTokenId); return nftToken; } /** * @dev called by the admin to pause, triggers stopped state */ function pause() public onlyAdminOrOperator whenNotPaused { _pause(); emit Pause(currentEpoch); } /** * @dev called by the admin to unpause, returns to normal state * Reset genesis state. Once paused, the rounds would need to be kickstarted by genesis */ function unpause() public onlyAdminOrOperator whenPaused { genesisStartOnce = false; genesisLockOnce = false; _unpause(); emit Unpause(currentEpoch); } /** * @dev Return round epochs that a user has participated */ function getUserRounds( address user, uint256 cursor, uint256 size ) external view returns (uint256[] memory, uint256) { uint256 length = size; if (length > userRounds[user].length - cursor) { length = userRounds[user].length - cursor; } uint256[] memory values = new uint256[](length); for (uint256 i = 0; i < length; i++) { values[i] = userRounds[user][cursor + i]; } return (values, cursor + length); } /** * @dev Get the claimable stats of specific epoch and user account */ function claimable(uint256 epoch, address user) public view returns (bool) { BetInfo memory betInfo = ledger[epoch][user]; Round memory round = rounds[epoch]; if (round.lockPrice == round.closePrice) { return false; } return round.oracleCalled && ((round.closePrice > round.lockPrice && betInfo.position == Position.Bull) || (round.closePrice < round.lockPrice && betInfo.position == Position.Bear)); } /** * @dev Get the refundable stats of specific epoch and user account */ function refundable(uint256 epoch, address user) public view returns (bool) { BetInfo memory betInfo = ledger[epoch][user]; Round memory round = rounds[epoch]; return !round.oracleCalled && block.number > round.endBlock.add(bufferBlocks) && betInfo.amount != 0; } function indexRound(uint256 epoch) external view returns( uint256 startBlock, uint256 lockBlock, uint256 endBlock, bool oracleCalled ) { if(epoch == 0) { epoch = currentEpoch; } Round memory round = rounds[epoch]; return (round.startBlock, round.lockBlock, round.endBlock, round.oracleCalled); } /** * @dev Start round * Previous round n-2 must end */ function _safeStartRound(uint256 epoch) internal { uint256 startBlock = getRoundStartBlock(); require(genesisStartOnce, "Can only run after genesisStartRound is triggered"); require(rounds[epoch - 2].endBlock != 0, "Can only start round after round n-2 has ended"); require(startBlock >= rounds[epoch - 2].lockBlock, "Can only start new round after round n-2 endBlock"); _startRound(epoch, startBlock); } function _startRound(uint256 epoch, uint256 startBlock) internal { Round storage round = rounds[epoch]; round.startBlock = startBlock; round.lockBlock = startBlock.add(intervalBlocks); round.endBlock = startBlock.add(intervalBlocks * 2); round.epoch = epoch; round.totalAmount = 0; emit StartRound(epoch, startBlock, intervalBlocks); } /** * @dev Lock round */ function _safeLockRound(uint256 epoch, int256 price) internal { require(rounds[epoch].startBlock != 0, "Can only lock round after round has started"); require(block.number >= rounds[epoch].lockBlock, "Can only lock round after lockBlock"); require(block.number <= rounds[epoch].lockBlock.add(bufferBlocks), "Can only lock round within bufferBlocks"); _lockRound(epoch, price); } function _lockRound(uint256 epoch, int256 price) internal { Round storage round = rounds[epoch]; round.lockPrice = price; emit LockRound(epoch, block.number, round.lockPrice); } /** * @dev End round */ function _safeEndRound(uint256 epoch, int256 price) internal { require(rounds[epoch].lockBlock != 0, "Can only end round after round has locked"); require(block.number.add(intervalBlocks) >= rounds[epoch].endBlock, "Can only end round after endBlock"); require(block.number <= rounds[epoch].endBlock.add(bufferBlocks), "Can only end round within bufferBlocks"); _endRound(epoch, price); } function _endRound(uint256 epoch, int256 price) internal { Round storage round = rounds[epoch]; round.closePrice = price; round.oracleCalled = true; emit EndRound(epoch, block.number, round.closePrice); } /** * @dev Calculate rewards for round */ function _calculateRewards(uint256 epoch) internal { require(rewardRate.add(treasuryRate) == TOTAL_RATE, "rewardRate and treasuryRate must add up to TOTAL_RATE"); require(rounds[epoch].rewardBaseCalAmount == 0 && rounds[epoch].rewardAmount == 0, "Rewards calculated"); Round storage round = rounds[epoch]; uint256 rewardBaseCalAmount; uint256 rewardAmount; // Bull wins if (round.closePrice > round.lockPrice) { rewardBaseCalAmount = round.bullAmount; rewardAmount = round.totalAmount.mul(rewardRate).div(TOTAL_RATE); } // Bear wins else if (round.closePrice < round.lockPrice) { rewardBaseCalAmount = round.bearAmount; rewardAmount = round.totalAmount.mul(rewardRate).div(TOTAL_RATE); } // House wins else { rewardBaseCalAmount = 0; rewardAmount = round.totalAmount.mul(rewardRate).div(TOTAL_RATE); if(rewardAmount > 0) { bonusSharePool.predictionBet(address(0x0), 0, rewardAmount); } } round.rewardBaseCalAmount = rewardBaseCalAmount; round.rewardAmount = rewardAmount; emit RewardsCalculated(epoch, rewardBaseCalAmount, rewardAmount, 0); } /** * */ function approveToStakingAddress() public onlyAdminOrOperator{ betToken.approve(address(bonusSharePool), ~uint256(0)); } /** * @dev Get latest recorded price from oracle * If it falls below allowed buffer or has not updated, it would be invalid */ function _getPriceFromOracle() internal returns (int256) { uint256 leastAllowedTimestamp = block.timestamp.add(oracleUpdateAllowance); (uint80 roundId, int256 price, , uint256 timestamp, ) = oracle.latestRoundData(); require(timestamp <= leastAllowedTimestamp, "Oracle update exceeded max timestamp allowance"); require(roundId > oracleLatestRoundId, "Oracle update roundId must be larger than oracleLatestRoundId"); oracleLatestRoundId = uint256(roundId); return price; } function _safeTransferBNB(address to, uint256 value) internal { (bool success, ) = to.call{gas: 23000, value: value}(""); require(success, "TransferHelper: BNB_TRANSFER_FAILED"); } function _isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } /** * @dev Determine if a round is valid for receiving bets * Round must have started and locked * Current block must be within startBlock and endBlock */ function _bettable(uint256 epoch) internal view returns (bool) { return rounds[epoch].startBlock != 0 && rounds[epoch].lockBlock != 0 && block.number >= rounds[epoch].startBlock && block.number < rounds[epoch].lockBlock; } //获取整点区块 function getRoundStartBlock() public view returns(uint256) { uint256 timeInterval = intervalBlocks * 3; uint256 mod = block.timestamp.mod(timeInterval); uint256 inBlock = mod.div(3); uint256 blockNumber = block.number; if(inBlock > 10 && blockNumber > inBlock) { return blockNumber - inBlock; } return blockNumber; } }
Start the next round n, lock price for round n-1, end round n-2/ CurrentEpoch refers to previous round (n-1) Increment currentEpoch to current round (n)
function executeRound() external onlyAdminOrOperator whenNotPaused { require( genesisStartOnce && genesisLockOnce, "Can only run after genesisStartRound and genesisLockRound is triggered" ); int256 currentPrice = _getPriceFromOracle(); _safeLockRound(currentEpoch, currentPrice); _safeEndRound(currentEpoch - 1, currentPrice); _calculateRewards(currentEpoch - 1); currentEpoch = currentEpoch + 1; _safeStartRound(currentEpoch); if(currentEpoch >= 5 && rounds[currentEpoch - 5].totalAmount == 0) { delete rounds[currentEpoch - 5]; } }
5,361,293
./full_match/1/0xDE3883c5d148Fb99Fc5b5a9D14AB88E793E20507/sources/PreachersCompFiLqdt.sol
The liquidator liquidates the borrower's collateral. The collateral seized is transferred to the liquidator. Checks if the liquidation should be allowed to occur cTokenBorrowed Asset which was borrowed by the borrower cTokenCollateral Asset which was used as collateral and will be seized liquidator The address repaying the borrow and seizing the collateral borrower The address of the borrower repayAmount The amount of underlying being repaid return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) function liquidateBorrowAllowed ( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns ( uint256 );/
function CheckLiquidation( address tokenBorrowed, address tokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns ( uint256 ) { Comptroller ctroll = Comptroller(kUnitroller); return ctroll.liquidateBorrowAllowed( tokenBorrowed, tokenCollateral, liquidator, borrower, repayAmount ); } event Liquidated(address account, address token, uint256 amount ); event PassThru( uint256 liquidateampount ); event Swapped(address fromtoken, uint256 fromamount, address totoken, uint256 toamount); event Transfer(address from, address to, uint256 value); event Withdrawn(address token, uint256 amount); event Received(address, uint);
17,107,923
// File: contracts/libraries/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function ADD545(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x + y) >= x, 'ds-math-add-overflow'); } function SUB798(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x - y) <= x, 'ds-math-sub-underflow'); } function MUL266(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/libraries/Math.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.6; // a library for performing various math operations library Math { function MIN959(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function SQRT138(uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event APPROVAL431(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER692(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME749() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL785() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS386() external view returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY975() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF40(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE51(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE455(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER497(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM392(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IHiposwapV1Callee.sol pragma solidity >=0.5.0; interface IHiposwapV1Callee { function HIPOSWAPV1CALL113(address sender, uint amount0, uint amount1, bytes calldata data) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IHiposwapV2Pair.sol pragma solidity >=0.5.0; interface IHiposwapV2Pair { event MINT336(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN633(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP682( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC847(uint reserve0, uint reserve1); //inject NONSTANDARD NAMING event _MAKER665(address indexed sender, address token, uint amount, uint time); //inject NONSTANDARD NAMING function FACTORY728() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0432() external view returns (address); //inject NONSTANDARD NAMING function TOKEN165() external view returns (address); //inject NONSTANDARD NAMING function CURRENTPOOLID0840() external view returns (uint); //inject NONSTANDARD NAMING function CURRENTPOOLID1169() external view returns (uint); //inject NONSTANDARD NAMING function GETMAKERPOOL0622(uint poolId) external view returns (uint _balance, uint _swapOut, uint _swapIn); //inject NONSTANDARD NAMING function GETMAKERPOOL1783(uint poolId) external view returns (uint _balance, uint _swapOut, uint _swapIn); //inject NONSTANDARD NAMING function GETRESERVES45() external view returns (uint reserve0, uint reserve1); //inject NONSTANDARD NAMING function GETBALANCE570() external view returns (uint _balance0, uint _balance1); //inject NONSTANDARD NAMING function GETMAKER873(address mkAddress) external view returns (uint,address,uint,uint); //inject NONSTANDARD NAMING function GETFEES121() external view returns (uint _fee0, uint _fee1); //inject NONSTANDARD NAMING function GETFEEADMINS69() external view returns (uint _feeAdmin0, uint _feeAdmin1); //inject NONSTANDARD NAMING function GETAVGTIMES842() external view returns (uint _avgTime0, uint _avgTime1); //inject NONSTANDARD NAMING function TRANSFERFEEADMIN813(address to) external; //inject NONSTANDARD NAMING function GETFEEPERCENTS417() external view returns (uint _feeAdminPercent, uint _feePercent, uint _totalPercent); //inject NONSTANDARD NAMING function SETFEEPERCENTS814(uint _feeAdminPercent, uint _feePercent, uint _totalPercent) external; //inject NONSTANDARD NAMING function GETREMAINPERCENT819() external view returns (uint); //inject NONSTANDARD NAMING function GETTOTALPERCENT249() external view returns (uint); //inject NONSTANDARD NAMING function SWAP628(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function ORDER543(address to) external returns (address token, uint amount); //inject NONSTANDARD NAMING function RETRIEVE897(uint amount0, uint amount1, address sender, address to) external returns (uint, uint); //inject NONSTANDARD NAMING function GETAMOUNTA17(address to, uint amountB) external view returns(uint amountA, uint _amountB, uint rewardsB, uint remainA); //inject NONSTANDARD NAMING function GETAMOUNTB418(address to, uint amountA) external view returns(uint _amountA, uint amountB, uint rewardsB, uint remainA); //inject NONSTANDARD NAMING function INITIALIZE162(address, address) external; //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract Context { function _MSGSENDER363() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA700() 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; } } // File: openzeppelin-solidity/contracts/access/Ownable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED266(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER363(); _owner = msgSender; emit OWNERSHIPTRANSFERRED266(address(0), msgSender); } function OWNER618() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER77() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER363(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP420() public virtual ONLYOWNER77 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED266(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP895(address newOwner) public virtual ONLYOWNER77 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED266(_owner, newOwner); _owner = newOwner; } } // File: contracts/HiposwapV2Pair.sol pragma solidity =0.6.6; contract HiposwapV2Pair is IHiposwapV2Pair, Ownable { using SafeMath for uint; bytes4 private constant selector578 = bytes4(keccak256(bytes('transfer(address,uint256)'))); //inject NONSTANDARD NAMING address public override factory; address public override token0; address public override token1; uint private fee0; uint private fee1; uint private feeAdmin0; uint private feeAdmin1; uint public totalWeightTime0; uint public totalWeightTime1; uint public totalTokens0; uint public totalTokens1; uint private avgTime0; uint private avgTime1; uint private reserve0; uint private reserve1; uint private feeAdminPercent = 5; uint private feePercent = 10; uint private totalPercent = 10000; struct MakerPool { uint balance; // remain tokenA uint swapOut; // swapped tokenA uint swapIn; // received tokenB uint createTime; } MakerPool[] public makerPools0; MakerPool[] public makerPools1; uint public override currentPoolId0; uint public override currentPoolId1; struct Maker { uint poolId; address token; uint amount; uint time; } mapping(address => Maker) private makers; uint public constant minimum_switch_pool_time31 = 30 minutes; //inject NONSTANDARD NAMING uint private unlocked = 1; modifier LOCK227() { //inject NONSTANDARD NAMING require(unlocked == 1, 'HiposwapV2Pair: LOCKED'); unlocked = 0; _; unlocked = 1; } function GETRESERVES45() public override view returns (uint _reserve0, uint _reserve1) { //inject NONSTANDARD NAMING _reserve0 = reserve0; _reserve1 = reserve1; } function GETFEES121() public override view returns (uint _fee0, uint _fee1) { //inject NONSTANDARD NAMING _fee0 = fee0; _fee1 = fee1; } function GETFEEADMINS69() public override view returns (uint _feeAdmin0, uint _feeAdmin1) { //inject NONSTANDARD NAMING _feeAdmin0 = feeAdmin0; _feeAdmin1 = feeAdmin1; } function GETAVGTIMES842() public override view returns (uint _avgTime0, uint _avgTime1) { //inject NONSTANDARD NAMING _avgTime0 = avgTime0; _avgTime1 = avgTime1; } function GETFEEPERCENTS417() public override view returns (uint _feeAdminPercent, uint _feePercent, uint _totalPercent) { //inject NONSTANDARD NAMING _feeAdminPercent = feeAdminPercent; _feePercent = feePercent; _totalPercent = totalPercent; } function GETREMAINPERCENT819() public override view returns (uint) { //inject NONSTANDARD NAMING return totalPercent.SUB798(feeAdminPercent).SUB798(feePercent); } function GETTOTALPERCENT249() external override view returns (uint) { //inject NONSTANDARD NAMING return totalPercent; } function SETFEEPERCENTS814(uint _feeAdminPercent, uint _feePercent, uint _totalPercent) public override ONLYOWNER77 { //inject NONSTANDARD NAMING require(_feeAdminPercent.ADD545(_feePercent) < _totalPercent, "HiposwapV2Pair: INVALID_PARAM"); feeAdminPercent = _feeAdminPercent; feePercent = _feePercent; totalPercent = _totalPercent; } function GETBALANCE570() public override view returns (uint _balance0, uint _balance1) { //inject NONSTANDARD NAMING _balance0 = IERC20(token0).BALANCEOF40(address(this)); _balance1 = IERC20(token1).BALANCEOF40(address(this)); } function GETMAKER873(address mkAddress) public override view returns (uint,address,uint,uint) { //inject NONSTANDARD NAMING Maker memory m = makers[mkAddress]; return (m.poolId, m.token, m.amount, m.time); } function GETMAKERPOOL0622(uint poolId) public override view returns (uint _balance, uint _swapOut, uint _swapIn) { //inject NONSTANDARD NAMING return _GETMAKERPOOL751(true, poolId); } function GETMAKERPOOL1783(uint poolId) public override view returns (uint _balance, uint _swapOut, uint _swapIn) { //inject NONSTANDARD NAMING return _GETMAKERPOOL751(false, poolId); } function _GETMAKERPOOL751(bool left, uint poolId) private view returns (uint _balance, uint _swapOut, uint _swapIn) { //inject NONSTANDARD NAMING MakerPool[] memory mps = left ? makerPools0 : makerPools1; if (mps.length > poolId) { MakerPool memory mp = mps[poolId]; return (mp.balance, mp.swapOut, mp.swapIn); } } function _SAFETRANSFER677(address token, address to, uint value) private { //inject NONSTANDARD NAMING (bool success, bytes memory data) = token.call(abi.encodeWithSelector(selector578, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'HiposwapV2Pair: TRANSFER_FAILED'); } event MINT336(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN633(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP682( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC847(uint reserve0, uint reserve1); //inject NONSTANDARD NAMING event _MAKER665(address indexed sender, address token, uint amount, uint time); //inject NONSTANDARD NAMING constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function INITIALIZE162(address _token0, address _token1) external override { //inject NONSTANDARD NAMING require(msg.sender == factory, 'HiposwapV2Pair: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } function CHECKMAKERPOOL614(bool left) private { //inject NONSTANDARD NAMING MakerPool[] storage mps = left ? makerPools0 : makerPools1; uint currentPoolId = left ? currentPoolId0 : currentPoolId1; if (mps.length > 0) { MakerPool storage mp = mps[currentPoolId]; if (mp.swapOut > mp.balance.MUL266(9) && now > mp.createTime.ADD545(minimum_switch_pool_time31)) { mps.push(MakerPool(0, 0, 0, now)); if (left) { currentPoolId0 = currentPoolId0.ADD545(1); mp.swapIn = mp.swapIn.ADD545(fee1); fee1 = 0; totalWeightTime0 = 0; totalTokens0 = 0; avgTime0 = 0; } else { currentPoolId1 = currentPoolId1.ADD545(1); mp.swapIn = mp.swapIn.ADD545(fee0); fee0 = 0; totalWeightTime1 = 0; totalTokens1 = 0; avgTime1 = 0; } } } else { mps.push(MakerPool(0, 0, 0, now)); } } function ADDFEE570(bool left, uint fee, uint feeAdmin) private { //inject NONSTANDARD NAMING if (left) { fee1 = fee1.ADD545(fee); feeAdmin1 = feeAdmin1.ADD545(feeAdmin); } else { fee0 = fee0.ADD545(fee); feeAdmin0 = feeAdmin0.ADD545(feeAdmin); } } function CHECKAVGTIME583(bool left, uint time) private view returns (bool isChargeFee) { //inject NONSTANDARD NAMING if (left) { if(avgTime0 > 0){ isChargeFee = now < time.ADD545(avgTime0); } } else { if(avgTime1 > 0){ isChargeFee = now < time.ADD545(avgTime1); } } } function UPDATEAVGTIME392(bool left, uint time, uint amount) private { //inject NONSTANDARD NAMING if(amount > 0 && now > time) { uint weight = (now - time).MUL266(amount); if (left) { uint _totalWeightTime0 = totalWeightTime0 + weight; if (_totalWeightTime0 >= totalWeightTime0) { totalWeightTime0 = _totalWeightTime0; totalTokens0 = totalTokens0.ADD545(amount); avgTime0 = totalWeightTime0 / totalTokens0; } else { // reset if overflow totalWeightTime0 = 0; totalTokens0 = 0; } } else { uint _totalWeightTime1 = totalWeightTime1 + weight; if (_totalWeightTime1 >= totalWeightTime1) { totalWeightTime1 = _totalWeightTime1; totalTokens1 = totalTokens1.ADD545(amount); avgTime1 = totalWeightTime1 / totalTokens1; } else { // reset if overflow totalWeightTime1 = 0; totalTokens1 = 0; } } } } function TRANSFERFEEADMIN813(address to) external override ONLYOWNER77{ //inject NONSTANDARD NAMING require(feeAdmin0 > 0 || feeAdmin1 > 0, "HiposwapV2Pair: EMPTY_ADMIN_FEES"); if (feeAdmin0 > 0) { _SAFETRANSFER677(token0, to, feeAdmin0); feeAdmin0 = 0; } if (feeAdmin1 > 0) { _SAFETRANSFER677(token1, to, feeAdmin1); feeAdmin1 = 0; } } function ORDER543(address to) external override LOCK227 returns (address token, uint amount){ //inject NONSTANDARD NAMING uint amount0 = IERC20(token0).BALANCEOF40(address(this)).SUB798(reserve0); uint amount1 = IERC20(token1).BALANCEOF40(address(this)).SUB798(reserve1); require((amount0 > 0 && amount1 == 0) || (amount0 == 0 && amount1 > 0), "HiposwapV2Pair: INVALID_AMOUNT"); bool left = amount0 > 0; CHECKMAKERPOOL614(left); Maker memory mk = makers[to]; if(mk.amount > 0) { require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN"); bool _left = mk.token == token0; uint _currentPoolId = _left ? currentPoolId0 : currentPoolId1; require(_currentPoolId >= mk.poolId, "HiposwapV2Pair: INVALID_POOL_ID"); if(_currentPoolId > mk.poolId){ DEAL573(to); mk.amount = 0; }else{ require(left == _left, "HiposwapV2Pair: ONLY_ONE_MAKER_ALLOWED"); } } uint currentPoolId = left ? currentPoolId0 : currentPoolId1; amount = left ? amount0 : amount1; token = left ? token0 : token1; makers[to] = Maker(currentPoolId, token, mk.amount.ADD545(amount), now); emit _MAKER665(to, token, amount, now); MakerPool storage mp = left ? makerPools0[currentPoolId] : makerPools1[currentPoolId]; mp.balance = mp.balance.ADD545(amount); (reserve0, reserve1) = GETBALANCE570(); } function DEAL573(address to) public { //inject NONSTANDARD NAMING Maker storage mk = makers[to]; require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN"); bool left = mk.token == token0; MakerPool storage mp = left ? makerPools0[mk.poolId] : makerPools1[mk.poolId]; (uint amountA, uint amountB) = (mk.amount, 0); if(mp.swapIn > 0 && mp.swapOut > 0){ amountB = Math.MIN959(mk.amount.MUL266(mp.swapIn) / mp.swapOut, mp.swapIn); uint swapOut = amountB.MUL266(mp.swapOut) / mp.swapIn; amountA = amountA.SUB798(swapOut); mp.swapIn = mp.swapIn.SUB798(amountB); mp.swapOut = mp.swapOut.SUB798(swapOut); } if (amountA > mp.balance) { // if swapOut, swapIn, balance = 3, 2, 0; mk.amount = 1; then amountB = 0, amountA = 1; uint dust = amountA.SUB798(mp.balance); ADDFEE570(!left, dust, 0); mp.swapOut = mp.swapOut.SUB798(dust); amountA = mp.balance; } mp.balance = mp.balance.SUB798(amountA); (uint amount0, uint amount1) = left ? (amountA, amountB) : (amountB, amountA); if(amount0 > 0){ _SAFETRANSFER677(token0, to, amount0); reserve0 = IERC20(token0).BALANCEOF40(address(this)); } if(amount1 > 0){ _SAFETRANSFER677(token1, to, amount1); reserve1 = IERC20(token1).BALANCEOF40(address(this)); } delete makers[to]; } function RETRIEVE897(uint amount0, uint amount1, address sender, address to) external override LOCK227 ONLYOWNER77 returns (uint, uint){ //inject NONSTANDARD NAMING require(amount0 > 0 || amount1 > 0, "HiposwapV2Pair: INVALID_AMOUNT"); Maker storage mk = makers[sender]; require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN"); bool left = mk.token == token0; MakerPool storage mp = left ? makerPools0[mk.poolId] : makerPools1[mk.poolId]; (uint amountA, uint amountB) = left ? (amount0, amount1) : (amount1, amount0); bool isChargeFee = mk.poolId == (left ? currentPoolId0 : currentPoolId1) && CHECKAVGTIME583(left, mk.time); uint amountOrigin = mk.amount; if (amountA > 0) { uint amountAMax = Math.MIN959(mk.amount, mp.balance); uint remain = GETREMAINPERCENT819(); amountAMax = isChargeFee ? amountAMax.MUL266(remain) / totalPercent : amountAMax; // 9985/10000 require(amountA <= amountAMax, "HiposwapV2Pair: INSUFFICIENT_AMOUNT"); if(isChargeFee){ uint fee = amountA.MUL266(feePercent) / remain; // 10/9985 uint feeAdmin = amountA.MUL266(feeAdminPercent) / remain; // = 5/9985 amountA = amountA.ADD545(fee).ADD545(feeAdmin); ADDFEE570(!left, fee, feeAdmin); } mk.amount = mk.amount.SUB798(amountA); mp.balance = mp.balance.SUB798(amountA); } if (amountB > 0) { require(mp.swapIn > 0 && mp.swapOut > 0, "HiposwapV2Pair: INSUFFICIENT_SWAP_BALANCE"); uint amountBMax = Math.MIN959(mp.swapIn, mk.amount.MUL266(mp.swapIn) / mp.swapOut); amountBMax = isChargeFee ? amountBMax.MUL266(GETREMAINPERCENT819()) / totalPercent : amountBMax; // 9985/10000 require(amountB <= amountBMax, "HiposwapV2Pair: INSUFFICIENT_SWAP_AMOUNT"); if(isChargeFee){ uint fee = amountB.MUL266(feePercent) / GETREMAINPERCENT819(); // 10/9985 uint feeAdmin = amountB.MUL266(feeAdminPercent) / GETREMAINPERCENT819(); // = 5/9985 amountB = amountB.ADD545(fee).ADD545(feeAdmin); ADDFEE570(left, fee, feeAdmin); }else if (mk.poolId == (left ? currentPoolId0 : currentPoolId1)) { uint rewards = amountB.MUL266(feePercent) / totalPercent; // 10/10000 if(left){ if (rewards > fee1) { rewards = fee1; } { uint _amount1 = amount1; amount1 = _amount1.ADD545(rewards); fee1 = fee1.SUB798(rewards); } }else{ if (rewards > fee0) { rewards = fee0; } {// avoid stack too deep uint _amount0 = amount0; amount0 = _amount0.ADD545(rewards); fee0 = fee0.SUB798(rewards); } } } uint _amountA = amountB.MUL266(mp.swapOut) / mp.swapIn; mp.swapIn = mp.swapIn.SUB798(amountB); mk.amount = mk.amount.SUB798(_amountA); mp.swapOut = mp.swapOut.SUB798(_amountA); } UPDATEAVGTIME392(left, mk.time, amountOrigin.SUB798(mk.amount)); if (mk.amount == 0) { delete makers[sender]; } if(amount0 > 0){ _SAFETRANSFER677(token0, to, amount0); reserve0 = IERC20(token0).BALANCEOF40(address(this)); } if(amount1 > 0){ _SAFETRANSFER677(token1, to, amount1); reserve1 = IERC20(token1).BALANCEOF40(address(this)); } return (amount0, amount1); } function GETMAKERANDPOOL128(address to) private view returns (Maker memory mk, MakerPool memory mp){ //inject NONSTANDARD NAMING mk = makers[to]; require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN"); bool left = mk.token == token0; uint poolId = mk.poolId; uint currentPoolId = left ? currentPoolId0 : currentPoolId1; require(poolId >= 0 && poolId <= currentPoolId, "HiposwapV2Pair: INVALID_POOL_ID"); mp = left ? makerPools0[poolId] : makerPools1[poolId]; } // amountB is exact function GETAMOUNTA17(address to, uint amountB) external override view returns(uint amountA, uint _amountB, uint rewardsB, uint remainA){ //inject NONSTANDARD NAMING (Maker memory mk, MakerPool memory mp) = GETMAKERANDPOOL128(to); bool left = mk.token == token0; uint currentPoolId = left ? currentPoolId0 : currentPoolId1; bool isChargeFee = mk.poolId == currentPoolId && CHECKAVGTIME583(left, mk.time); uint remain = GETREMAINPERCENT819(); if(amountB > 0){ if(mp.swapIn > 0 && mp.swapOut > 0){ uint mkAmount = isChargeFee ? mk.amount.MUL266(remain) / totalPercent : mk.amount; // 9985/10000 uint swapIn = isChargeFee ? mp.swapIn.MUL266(remain) / totalPercent : mp.swapIn; uint amountBMax = Math.MIN959(amountB, Math.MIN959(swapIn, mkAmount.MUL266(mp.swapIn) / mp.swapOut)); uint amountAMax = amountBMax.MUL266(mp.swapOut) / mp.swapIn; amountAMax = isChargeFee ? amountAMax.MUL266(totalPercent) / remain : amountAMax; mk.amount = mk.amount.SUB798(amountAMax); _amountB = amountBMax; if (!isChargeFee && mk.poolId == currentPoolId) { uint tmp = _amountB; // avoid stack too deep uint rewards = tmp.MUL266(feePercent) / totalPercent; if(left){ if (rewards > fee1) { rewards = fee1; } }else{ if (rewards > fee0) { rewards = fee0; } } rewardsB = rewards; } } } amountA = Math.MIN959(mk.amount, mp.balance); remainA = mk.amount.SUB798(amountA); amountA = isChargeFee ? amountA.MUL266(remain) / totalPercent : amountA; } // amountA is exact function GETAMOUNTB418(address to, uint amountA) external override view returns(uint _amountA, uint amountB, uint rewardsB, uint remainA){ //inject NONSTANDARD NAMING (Maker memory mk, MakerPool memory mp) = GETMAKERANDPOOL128(to); bool left = mk.token == token0; uint currentPoolId = left ? currentPoolId0 : currentPoolId1; bool isChargeFee = mk.poolId == currentPoolId && CHECKAVGTIME583(left, mk.time); uint remain = GETREMAINPERCENT819(); if(amountA > 0){ uint mkAmount = isChargeFee ? mk.amount.MUL266(remain) / totalPercent : mk.amount; uint mpBalance = isChargeFee ? mp.balance.MUL266(remain) / totalPercent : mp.balance; _amountA = Math.MIN959(Math.MIN959(amountA, mkAmount), mpBalance); if (_amountA == mkAmount) { mk.amount = 0; } else { mk.amount = mk.amount.SUB798(isChargeFee ? _amountA.MUL266(totalPercent) / remain : _amountA); } } if(mp.swapIn > 0 && mp.swapOut > 0){ amountB = Math.MIN959(mp.swapIn, mk.amount.MUL266(mp.swapIn) / mp.swapOut); mk.amount = mk.amount.SUB798(amountB.MUL266(mp.swapOut) / mp.swapIn); if (isChargeFee) { amountB = amountB.MUL266(remain) / totalPercent; } else if (mk.poolId == currentPoolId) { uint rewards = amountB.MUL266(feePercent) / totalPercent; if(left){ if (rewards > fee1) { rewards = fee1; } }else{ if (rewards > fee0) { rewards = fee0; } } rewardsB = rewards; } } remainA = mk.amount; } function _UPDATE379(uint balance0, uint balance1) private { //inject NONSTANDARD NAMING require(balance0 <= uint(-1) && balance1 <= uint(-1), 'HiposwapV2Pair: OVERFLOW'); reserve0 = balance0; reserve1 = balance1; emit SYNC847(reserve0, reserve1); } function SWAP628(uint amount0Out, uint amount1Out, address to, bytes calldata data) external override LOCK227 { //inject NONSTANDARD NAMING require(amount0Out > 0 || amount1Out > 0, 'HiposwapV2Pair: INSUFFICIENT_OUTPUT_AMOUNT'); (uint _reserve0, uint _reserve1) = GETRESERVES45(); // gas savings require(amount0Out <= _reserve0 && amount1Out <= _reserve1, 'HiposwapV2Pair: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'HiposwapV2Pair: INVALID_TO'); if (amount0Out > 0) _SAFETRANSFER677(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _SAFETRANSFER677(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IHiposwapV1Callee(to).HIPOSWAPV1CALL113(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).BALANCEOF40(address(this)); balance1 = IERC20(_token1).BALANCEOF40(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'HiposwapV2Pair: INSUFFICIENT_INPUT_AMOUNT'); if (amount0In > 0) { uint fee = amount0In.MUL266(feePercent) / totalPercent; // = 10/10000 uint feeAdmin = amount0In.MUL266(feeAdminPercent) / totalPercent; // = 5/10000 uint swapIn = amount0In.SUB798(fee).SUB798(feeAdmin); MakerPool storage mp = makerPools1[currentPoolId1]; mp.swapIn = mp.swapIn.ADD545(swapIn); mp.swapOut = mp.swapOut.ADD545(amount1Out); mp.balance = mp.balance.SUB798(amount1Out); ADDFEE570(false, fee, feeAdmin); } if (amount1In >0) { uint fee = amount1In.MUL266(feePercent) / totalPercent; // = 10/10000 uint feeAdmin = amount1In.MUL266(feeAdminPercent) / totalPercent; // = 5/10000 uint swapIn = amount1In.SUB798(fee).SUB798(feeAdmin); MakerPool storage mp = makerPools0[currentPoolId0]; mp.swapIn = mp.swapIn.ADD545(swapIn); mp.swapOut = mp.swapOut.ADD545(amount0Out); mp.balance = mp.balance.SUB798(amount0Out); ADDFEE570(true, fee, feeAdmin); } _UPDATE379(balance0, balance1); emit SWAP682(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } } // File: contracts/interfaces/IHiposwapV2Util.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.6; interface IHiposwapV2Util { function PAIRCREATIONCODE232() external returns (bytes memory bytecode); //inject NONSTANDARD NAMING } // File: contracts/HiposwapV2Util.sol // SPDX-License-Identifier: MIT pragma solidity =0.6.6; contract HiposwapV2Util is IHiposwapV2Util { function PAIRCREATIONCODE232() external override returns (bytes memory bytecode){ //inject NONSTANDARD NAMING bytecode = type(HiposwapV2Pair).creationCode; } }
inject NONSTANDARD NAMING
function ALLOWANCE51(address owner, address spender) external view returns (uint);
7,324,409
./full_match/4/0xf15046F9c0ec667B016DAcb5D198000E1d20E337/sources/contracts/Marsh_Staking_Contract.sol
Function called in the event that an indexer is badly behaving. can only be triggered by an admin, results in a `SlashStakeEvent` than splits the indexer's stake between the reporter and the owner. _indexerAddress address of the indexer getting slashed reporterAddress address of the reporter/
function RemoveStake(address _indexerAddress, address reporterAddress) external onlyAdmin { require( _indexerExists(_indexerAddress), "Indexer must exist and have staked" ); string memory pkey = approvedIndexers[_indexerAddress].indexerPublicKey; approvedIndexers[_indexerAddress].hasStaked = false; numActiveIndexers--; uint256 totalAmount = approvedIndexers[_indexerAddress].stakeAmount; approvedIndexers[_indexerAddress].stakeAmount = 0; _transferStake(reporterAddress, totalAmount); emit SlashStakeEvent(_indexerAddress, pkey, totalAmount, reporterAddress); }
688,638
./partial_match/1/0xd9b7eC74C06c558A59AfdE6a16E614950730F44d/sources/contracts/engine/V3/GenArt721CoreV3_Engine_Flex.sol
Gets royalty Basis Points (BPS) for token ID `_tokenId`. This conforms to the IManifold interface designated in the Royalty Registry's RoyaltyEngineV1.sol contract. _tokenId Token ID to be queried. return recipients Array of royalty payment recipients return bps Array of Basis Points (BPS) allocated to each recipient, aligned by index. reverts if invalid _tokenId only returns recipients that have a non-zero BPS allocation/ initialize arrays with maximum potential length load values into memory calculate BPS = percentage 100 populate arrays trim arrays if necessary
function getRoyalties( uint256 _tokenId ) external view returns (address payable[] memory recipients, uint256[] memory bps) { _onlyValidTokenId(_tokenId); recipients = new address payable[](4); bps = new uint256[](4); uint256 projectId = tokenIdToProjectId(_tokenId); ProjectFinance storage projectFinance = projectIdToFinancials[ projectId ]; uint256 royaltyPercentageForArtistAndAdditional = projectFinance .secondaryMarketRoyaltyPercentage; uint256 additionalPayeePercentage = projectFinance .additionalPayeeSecondarySalesPercentage; uint256 artistBPS = (ONE_HUNDRED - additionalPayeePercentage) * royaltyPercentageForArtistAndAdditional; uint256 additionalBPS = additionalPayeePercentage * royaltyPercentageForArtistAndAdditional; uint256 renderProviderBPS = renderProviderSecondarySalesBPS; uint256 platformProviderBPS = platformProviderSecondarySalesBPS; uint256 payeeCount; if (artistBPS > 0) { recipients[payeeCount] = projectFinance.artistAddress; bps[payeeCount++] = artistBPS; } if (additionalBPS > 0) { recipients[payeeCount] = projectFinance .additionalPayeeSecondarySales; bps[payeeCount++] = additionalBPS; } if (renderProviderBPS > 0) { recipients[payeeCount] = renderProviderSecondarySalesAddress; bps[payeeCount++] = renderProviderBPS; } if (platformProviderBPS > 0) { recipients[payeeCount] = platformProviderSecondarySalesAddress; bps[payeeCount++] = platformProviderBPS; } if (4 > payeeCount) { assembly { let decrease := sub(4, payeeCount) mstore(recipients, sub(mload(recipients), decrease)) mstore(bps, sub(mload(bps), decrease)) } } return (recipients, bps); }
3,903,922
//Address: 0xa3958375Aa3B1494faE8D53dc4a074232801bBBe //Contract name: STQPreICO3 //Balance: 0 Ether //Verification Date: 10/28/2017 //Transacion Count: 17 // CODE STARTS HERE pragma solidity 0.4.15; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /// note: during any ownership changes all pending operations (waiting for more signatures) are cancelled // TODO acceptOwnership contract multiowned { // TYPES // struct for the status of a pending operation. struct MultiOwnedOperationPendingState { // count of confirmations needed uint yetNeeded; // bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit uint ownersDone; // position of this operation key in m_multiOwnedPendingIndex uint index; } // EVENTS event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { require(isOwner(msg.sender)); _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } // Even if required number of confirmations has't been collected yet, // we can't throw here - because changes to the state have to be preserved. // But, confirmAndCheck itself will throw in case sender is not an owner. } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!). function multiowned(address[] _owners, uint _required) validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; // invalid and duplicate addresses are not allowed require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } /// @notice replaces an owner `_from` with another `_to`. /// @param _from address of owner to replace /// @param _to address of new owner // All pending operations will be canceled! function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlymanyowners(sha3(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); OwnerChanged(_from, _to); } /// @notice adds an owner /// @param _owner address of new owner // All pending operations will be canceled! function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlymanyowners(sha3(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); OwnerAdded(_owner); } /// @notice removes an owner /// @param _owner address of owner to remove // All pending operations will be canceled! function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlymanyowners(sha3(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = 0; m_ownerIndex[_owner] = 0; //make sure m_numOwners is equal to the number of owners and always points to the last owner reorganizeOwners(); assertOwnersAreConsistent(); OwnerRemoved(_owner); } /// @notice changes the required number of owner signatures /// @param _newRequired new number of signatures required // All pending operations will be canceled! function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(sha3(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); RequirementChanged(_newRequired); } /// @notice Gets an owner by 0-indexed position /// @param ownerIndex 0-indexed owner position function getOwner(uint ownerIndex) public constant returns (address) { return m_owners[ownerIndex + 1]; } /// @notice Gets owners /// @return memory array of owners function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } /// @notice checks if provided address is an owner address /// @param _addr address to check /// @return true if it's an owner function isOwner(address _addr) public constant returns (bool) { return m_ownerIndex[_addr] > 0; } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external constant onlyowner returns (bool) { return true; } /// @notice Revokes a prior confirmation of the given operation /// @param _operation operation value, typically sha3(msg.data) function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); var pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); Revoke(msg.sender, _operation); } /// @notice Checks if owner confirmed given operation /// @param _operation operation value, typically sha3(msg.data) /// @param _owner an owner address function hasConfirmed(bytes32 _operation, address _owner) external constant multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) // In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point // we won't be able to do it because of block gas limit. // Yes, pending confirmations will be lost. Dont see any security or stability implications. // TODO use more graceful approach like compact or removal of clearPending completely clearPending(); var pending = m_multiOwnedPending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (! isOperationActive(_operation)) { // reset count of confirmations needed. pending.yetNeeded = m_multiOwnedRequired; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } // determine the bit to set for this owner. uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { // ok - check if count is enough to go ahead. assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } } } // Reclaims free slots between valid owners in m_owners. // TODO given that its called after each removal, it could be simplified. function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { // iterating to the first free slot from the beginning while (free < m_numOwners && m_owners[free] != 0) free++; // iterating to the first occupied slot from the end while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; // swap, if possible, so free slot is located at the end after the swap if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { // owners between swapped slots should't be renumbered - that saves a lot of gas m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private constant returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private constant returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private constant returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private constant { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == 0); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private constant { var pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } // FIELDS uint constant c_maxOwners = 250; // the number of owners that must confirm the same operation before it is run. uint public m_multiOwnedRequired; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners (addresses), // slot 0 is unused so there are no owner which index is 0. // TODO could we save space at the end of the array for the common case of <10 owners? and should we? address[256] internal m_owners; // index on the list of owners to allow reverse lookup: owner address => index in m_owners mapping(address => uint) internal m_ownerIndex; // the ongoing operations. mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; bytes32[] internal m_multiOwnedPendingIndex; } /** * @title Contract which is owned by owners and operated by controller. * * @notice Provides a way to set up an entity (typically other contract) entitled to control actions of this contract. * Controller is set up by owners or during construction. * * @dev controller check is performed by onlyController modifier. */ contract MultiownedControlled is multiowned { event ControllerSet(address controller); event ControllerRetired(address was); modifier onlyController { require(msg.sender == m_controller); _; } // PUBLIC interface function MultiownedControlled(address[] _owners, uint _signaturesRequired, address _controller) multiowned(_owners, _signaturesRequired) { m_controller = _controller; ControllerSet(m_controller); } /// @dev sets the controller function setController(address _controller) external onlymanyowners(sha3(msg.data)) { m_controller = _controller; ControllerSet(m_controller); } /// @dev ability for controller to step down function detachController() external onlyController { address was = m_controller; m_controller = address(0); ControllerRetired(was); } // FIELDS /// @notice address of entity entitled to mint new tokens address public m_controller; } /// @title StandardToken which can be minted by another contract. contract MintableMultiownedToken is MultiownedControlled, StandardToken { /// @dev parameters of an extra token emission struct EmissionInfo { // tokens created uint256 created; // totalSupply at the moment of emission (excluding created tokens) uint256 totalSupplyWas; } event Mint(address indexed to, uint256 amount); event Emission(uint256 tokensCreated, uint256 totalSupplyWas, uint256 time); event Dividend(address indexed to, uint256 amount); // PUBLIC interface function MintableMultiownedToken(address[] _owners, uint _signaturesRequired, address _minter) MultiownedControlled(_owners, _signaturesRequired, _minter) { dividendsPool = this; // or any other special unforgeable value, actually // emission #0 is a dummy: because of default value 0 in m_lastAccountEmission m_emissions.push(EmissionInfo({created: 0, totalSupplyWas: 0})); } /// @notice Request dividends for current account. function requestDividends() external { payDividendsTo(msg.sender); } /// @notice hook on standard ERC20#transfer to pay dividends function transfer(address _to, uint256 _value) returns (bool) { payDividendsTo(msg.sender); payDividendsTo(_to); return super.transfer(_to, _value); } /// @notice hook on standard ERC20#transferFrom to pay dividends function transferFrom(address _from, address _to, uint256 _value) returns (bool) { payDividendsTo(_from); payDividendsTo(_to); return super.transferFrom(_from, _to, _value); } // Disabled: this could be undesirable because sum of (balanceOf() for each token owner) != totalSupply // (but: sum of (balances[owner] for each token owner) == totalSupply!). // // @notice hook on standard ERC20#balanceOf to take dividends into consideration // function balanceOf(address _owner) constant returns (uint256) { // var (hasNewDividends, dividends) = calculateDividendsFor(_owner); // return hasNewDividends ? super.balanceOf(_owner).add(dividends) : super.balanceOf(_owner); // } /// @dev mints new tokens function mint(address _to, uint256 _amount) external onlyController { require(m_externalMintingEnabled); payDividendsTo(_to); mintInternal(_to, _amount); } /// @dev disables mint(), irreversible! function disableMinting() external onlyController { require(m_externalMintingEnabled); m_externalMintingEnabled = false; } // INTERNAL functions /** * @notice Starts new token emission * @param _tokensCreated Amount of tokens to create * @dev Dividends are not distributed immediately as it could require billions of gas, * instead they are `pulled` by a holder from dividends pool account before any update to the holder account occurs. */ function emissionInternal(uint256 _tokensCreated) internal { require(0 != _tokensCreated); require(_tokensCreated < totalSupply / 2); // otherwise it looks like an error uint256 totalSupplyWas = totalSupply; m_emissions.push(EmissionInfo({created: _tokensCreated, totalSupplyWas: totalSupplyWas})); mintInternal(dividendsPool, _tokensCreated); Emission(_tokensCreated, totalSupplyWas, now); } function mintInternal(address _to, uint256 _amount) internal { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(this, _to, _amount); Mint(_to, _amount); } /// @dev adds dividends to the account _to function payDividendsTo(address _to) internal { var (hasNewDividends, dividends) = calculateDividendsFor(_to); if (!hasNewDividends) return; if (0 != dividends) { balances[dividendsPool] = balances[dividendsPool].sub(dividends); balances[_to] = balances[_to].add(dividends); Transfer(dividendsPool, _to, dividends); } m_lastAccountEmission[_to] = getLastEmissionNum(); } /// @dev calculates dividends for the account _for /// @return (true if state has to be updated, dividend amount (could be 0!)) function calculateDividendsFor(address _for) constant internal returns (bool hasNewDividends, uint dividends) { assert(_for != dividendsPool); // no dividends for the pool! uint256 lastEmissionNum = getLastEmissionNum(); uint256 lastAccountEmissionNum = m_lastAccountEmission[_for]; assert(lastAccountEmissionNum <= lastEmissionNum); if (lastAccountEmissionNum == lastEmissionNum) return (false, 0); uint256 initialBalance = balances[_for]; // beware of recursion! if (0 == initialBalance) return (true, 0); uint256 balance = initialBalance; for (uint256 emissionToProcess = lastAccountEmissionNum + 1; emissionToProcess <= lastEmissionNum; emissionToProcess++) { EmissionInfo storage emission = m_emissions[emissionToProcess]; assert(0 != emission.created && 0 != emission.totalSupplyWas); uint256 dividend = balance.mul(emission.created).div(emission.totalSupplyWas); Dividend(_for, dividend); balance = balance.add(dividend); } return (true, balance.sub(initialBalance)); } function getLastEmissionNum() private constant returns (uint256) { return m_emissions.length - 1; } // FIELDS /// @notice if this true then token is still externally mintable (but this flag does't affect emissions!) bool public m_externalMintingEnabled = true; /// @dev internal address of dividends in balances mapping. address dividendsPool; /// @notice record of issued dividend emissions EmissionInfo[] public m_emissions; /// @dev for each token holder: last emission (index in m_emissions) which was processed for this holder mapping(address => uint256) m_lastAccountEmission; } /// @title utility methods and modifiers of arguments validation contract ArgumentsChecker { /// @dev check which prevents short address attack modifier payloadSizeIs(uint size) { require(msg.data.length == size + 4 /* function selector */); _; } /// @dev check that address is valid modifier validAddress(address addr) { require(addr != address(0)); _; } } /** * @title Interface for code which processes and stores investments. * @author Eenae */ contract IInvestmentsWalletConnector { /// @dev process and forward investment function storeInvestment(address investor, uint payment) internal; /// @dev total investments amount stored using storeInvestment() function getTotalInvestmentsStored() internal constant returns (uint); /// @dev called in case crowdsale succeeded function wcOnCrowdsaleSuccess() internal; /// @dev called in case crowdsale failed function wcOnCrowdsaleFailure() internal; } /** * @title Stores investments in specified external account. * @author Eenae */ contract ExternalAccountWalletConnector is ArgumentsChecker, IInvestmentsWalletConnector { function ExternalAccountWalletConnector(address accountAddress) validAddress(accountAddress) { m_walletAddress = accountAddress; } /// @dev process and forward investment function storeInvestment(address /*investor*/, uint payment) internal { m_wcStored += payment; m_walletAddress.transfer(payment); } /// @dev total investments amount stored using storeInvestment() function getTotalInvestmentsStored() internal constant returns (uint) { return m_wcStored; } /// @dev called in case crowdsale succeeded function wcOnCrowdsaleSuccess() internal { } /// @dev called in case crowdsale failed function wcOnCrowdsaleFailure() internal { } /// @notice address of wallet which stores funds address public m_walletAddress; /// @notice total investments stored to wallet uint public m_wcStored; } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* * @title This is proxy for analytics. Target contract can be found at field m_analytics (see "read contract"). * @author Eenae * FIXME after fix of truffle issue #560: refactor to a separate contract file which uses InvestmentAnalytics interface */ contract AnalyticProxy { function AnalyticProxy() { m_analytics = InvestmentAnalytics(msg.sender); } /// @notice forward payment to analytics-capable contract function() payable { m_analytics.iaInvestedBy.value(msg.value)(msg.sender); } InvestmentAnalytics public m_analytics; } /* * @title Mixin contract which supports different payment channels and provides analytical per-channel data. * @author Eenae */ contract InvestmentAnalytics { using SafeMath for uint256; function InvestmentAnalytics(){ } /// @dev creates more payment channels, up to the limit but not exceeding gas stipend function createMorePaymentChannelsInternal(uint limit) internal returns (uint) { uint paymentChannelsCreated; for (uint i = 0; i < limit; i++) { uint startingGas = msg.gas; /* * ~170k of gas per paymentChannel, * using gas price = 4Gwei 2k paymentChannels will cost ~1.4 ETH. */ address paymentChannel = new AnalyticProxy(); m_validPaymentChannels[paymentChannel] = true; m_paymentChannels.push(paymentChannel); paymentChannelsCreated++; // cost of creating one channel uint gasPerChannel = startingGas.sub(msg.gas); if (gasPerChannel.add(50000) > msg.gas) break; // enough proxies for this call } return paymentChannelsCreated; } /// @dev process payments - record analytics and pass control to iaOnInvested callback function iaInvestedBy(address investor) external payable { address paymentChannel = msg.sender; if (m_validPaymentChannels[paymentChannel]) { // payment received by one of our channels uint value = msg.value; m_investmentsByPaymentChannel[paymentChannel] = m_investmentsByPaymentChannel[paymentChannel].add(value); // We know for sure that investment came from specified investor (see AnalyticProxy). iaOnInvested(investor, value, true); } else { // Looks like some user has paid to this method, this payment is not included in the analytics, // but, of course, processed. iaOnInvested(msg.sender, msg.value, false); } } /// @dev callback function iaOnInvested(address /*investor*/, uint /*payment*/, bool /*usingPaymentChannel*/) internal { } function paymentChannelsCount() external constant returns (uint) { return m_paymentChannels.length; } function readAnalyticsMap() external constant returns (address[], uint[]) { address[] memory keys = new address[](m_paymentChannels.length); uint[] memory values = new uint[](m_paymentChannels.length); for (uint i = 0; i < m_paymentChannels.length; i++) { address key = m_paymentChannels[i]; keys[i] = key; values[i] = m_investmentsByPaymentChannel[key]; } return (keys, values); } function readPaymentChannels() external constant returns (address[]) { return m_paymentChannels; } mapping(address => uint256) public m_investmentsByPaymentChannel; mapping(address => bool) m_validPaymentChannels; address[] public m_paymentChannels; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Basic crowdsale stat * @author Eenae */ contract ICrowdsaleStat { /// @notice amount of funds collected in wei function getWeiCollected() public constant returns (uint); /// @notice amount of tokens minted (NOT equal to totalSupply() in case token is reused!) function getTokenMinted() public constant returns (uint); } /** * @title Helps contracts guard agains rentrancy attacks. * @author Remco Bloemen <remco@2π.com> * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private rentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } } /// @title Base contract for simple crowdsales contract SimpleCrowdsaleBase is ArgumentsChecker, ReentrancyGuard, IInvestmentsWalletConnector, ICrowdsaleStat { using SafeMath for uint256; event FundTransfer(address backer, uint amount, bool isContribution); function SimpleCrowdsaleBase(address token) validAddress(token) { m_token = MintableMultiownedToken(token); } // PUBLIC interface: payments // fallback function as a shortcut function() payable { require(0 == msg.data.length); buy(); // only internal call here! } /// @notice crowdsale participation function buy() public payable { // dont mark as external! buyInternal(msg.sender, msg.value, 0); } // INTERNAL /// @dev payment processing function buyInternal(address investor, uint payment, uint extraBonuses) internal nonReentrant { require(payment >= getMinInvestment()); require(getCurrentTime() >= getStartTime() || ! mustApplyTimeCheck(investor, payment) /* for final check */); if (getCurrentTime() >= getEndTime()) finish(); if (m_finished) { // saving provided gas investor.transfer(payment); return; } uint startingWeiCollected = getWeiCollected(); uint startingInvariant = this.balance.add(startingWeiCollected); // return or update payment if needed uint paymentAllowed = getMaximumFunds().sub(getWeiCollected()); assert(0 != paymentAllowed); uint change; if (paymentAllowed < payment) { change = payment.sub(paymentAllowed); payment = paymentAllowed; } // issue tokens uint tokens = calculateTokens(investor, payment, extraBonuses); m_token.mint(investor, tokens); m_tokensMinted += tokens; // record payment storeInvestment(investor, payment); assert(getWeiCollected() <= getMaximumFunds() && getWeiCollected() > startingWeiCollected); FundTransfer(investor, payment, true); if (getWeiCollected() == getMaximumFunds()) finish(); if (change > 0) investor.transfer(change); assert(startingInvariant == this.balance.add(getWeiCollected()).add(change)); } function finish() internal { if (m_finished) return; if (getWeiCollected() >= getMinimumFunds()) wcOnCrowdsaleSuccess(); else wcOnCrowdsaleFailure(); m_finished = true; } // Other pluggables /// @dev says if crowdsale time bounds must be checked function mustApplyTimeCheck(address /*investor*/, uint /*payment*/) constant internal returns (bool) { return true; } /// @dev to be overridden in tests function getCurrentTime() internal constant returns (uint) { return now; } /// @notice maximum investments to be accepted during pre-ICO function getMaximumFunds() internal constant returns (uint); /// @notice minimum amount of funding to consider crowdsale as successful function getMinimumFunds() internal constant returns (uint); /// @notice start time of the pre-ICO function getStartTime() internal constant returns (uint); /// @notice end time of the pre-ICO function getEndTime() internal constant returns (uint); /// @notice minimal amount of investment function getMinInvestment() public constant returns (uint) { return 10 finney; } /// @dev calculates token amount for given investment function calculateTokens(address investor, uint payment, uint extraBonuses) internal constant returns (uint); // ICrowdsaleStat function getWeiCollected() public constant returns (uint) { return getTotalInvestmentsStored(); } /// @notice amount of tokens minted (NOT equal to totalSupply() in case token is reused!) function getTokenMinted() public constant returns (uint) { return m_tokensMinted; } // FIELDS /// @dev contract responsible for token accounting MintableMultiownedToken public m_token; uint m_tokensMinted; bool m_finished = false; } /// @title Base contract for Storiqa pre-ICO contract STQPreICOBase is SimpleCrowdsaleBase, Ownable, InvestmentAnalytics { function STQPreICOBase(address token) SimpleCrowdsaleBase(token) { } // PUBLIC interface: maintenance function createMorePaymentChannels(uint limit) external onlyOwner returns (uint) { return createMorePaymentChannelsInternal(limit); } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external constant onlyOwner returns (bool) { return true; } // INTERNAL /// @dev payment callback function iaOnInvested(address investor, uint payment, bool usingPaymentChannel) internal { buyInternal(investor, payment, usingPaymentChannel ? c_paymentChannelBonusPercent : 0); } function calculateTokens(address /*investor*/, uint payment, uint extraBonuses) internal constant returns (uint) { uint bonusPercent = getPreICOBonus().add(getLargePaymentBonus(payment)).add(extraBonuses); uint rate = c_STQperETH.mul(bonusPercent.add(100)).div(100); return payment.mul(rate); } function getLargePaymentBonus(uint payment) private constant returns (uint) { if (payment >= 5000 ether) return 20; if (payment >= 3000 ether) return 15; if (payment >= 1000 ether) return 10; if (payment >= 800 ether) return 8; if (payment >= 500 ether) return 5; if (payment >= 200 ether) return 2; return 0; } function mustApplyTimeCheck(address investor, uint /*payment*/) constant internal returns (bool) { return investor != owner; } /// @notice pre-ICO bonus function getPreICOBonus() internal constant returns (uint); // FIELDS /// @notice starting exchange rate of STQ uint public constant c_STQperETH = 100000; /// @notice authorised payment bonus uint public constant c_paymentChannelBonusPercent = 2; } /// @title Storiqa pre-ICO contract contract STQPreICO3 is STQPreICOBase, ExternalAccountWalletConnector { function STQPreICO3(address token, address wallet) STQPreICOBase(token) ExternalAccountWalletConnector(wallet) { } // INTERNAL function getWeiCollected() public constant returns (uint) { return getTotalInvestmentsStored(); } /// @notice minimum amount of funding to consider crowdsale as successful function getMinimumFunds() internal constant returns (uint) { return 0; } /// @notice maximum investments to be accepted during pre-ICO function getMaximumFunds() internal constant returns (uint) { return 100000000 ether; } /// @notice start time of the pre-ICO function getStartTime() internal constant returns (uint) { return 1508958000; // 2017-10-25 19:00:00 } /// @notice end time of the pre-ICO function getEndTime() internal constant returns (uint) { return 1511568000; //2017-11-25 00:00:00 } /// @notice pre-ICO bonus function getPreICOBonus() internal constant returns (uint) { return 33; } }
Request dividends for current account.
function requestDividends() external { payDividendsTo(msg.sender); }
5,416,963
./partial_match/97/0x88422CC30E020074f36b933E0Cd4d3041D6B4Fa5/sources/project_/contracts/DecubateMasterChef.sol
safe TOKEN transfer function, require to have enough TOKEN to transfer/
function safeTOKENTransfer( address _token, address _to, uint256 _amount ) internal { IERC20Upgradeable token = IERC20Upgradeable(_token); uint256 bal = token.balanceOf(address(this)); require(bal >= _amount, "Not enough funds in treasury"); uint256 maxTx = maxTransferAmount[_token]; uint256 amount = _amount; while (amount > maxTx) { token.transfer(_to, maxTx); amount = amount - maxTx; } if (amount > 0) { token.transfer(_to, amount); } }
11,353,322
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { AbstractCFATokenV2 } from "./AbstractCFATokenV2.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP712 } from "../util/EIP712.sol"; /** * @title EIP-3009 * @notice Provide internal implementation for gas-abstracted transfers * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ abstract contract EIP3009 is AbstractCFATokenV2, EIP712Domain { // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; /** * @dev authorizer address => nonce => bool (true if nonce is used) */ mapping(address => mapping(bytes32 => bool)) private _authorizationStates; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled( address indexed authorizer, bytes32 indexed nonce ); /** * @notice Returns the state of an authorization * @dev Nonces are randomly generated 32-byte data unique to the * authorizer's address * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return True if the nonce is used */ function authorizationState(address authorizer, bytes32 nonce) external view returns (bool) { return _authorizationStates[authorizer][nonce]; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "CFATokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { require(to == msg.sender, "CFATokenV2: caller must be the payee"); _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "CFATokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode( CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer, "CFATokenV2: invalid signature" ); _authorizationStates[authorizer][nonce] = true; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( !_authorizationStates[authorizer][nonce], "CFATokenV2: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require(now > validAfter, "CFATokenV2: authorization is not yet valid"); require(now < validBefore, "CFATokenV2: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { _authorizationStates[authorizer][nonce] = true; emit AuthorizationUsed(authorizer, nonce); } }
Check that authorization is valid authorizer Authorizer's address nonce Nonce of the authorization validAfter The time after which this is valid (unix time) validBefore The time before which this is valid (unix time)/
function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require(now > validAfter, "CFATokenV2: authorization is not yet valid"); require(now < validBefore, "CFATokenV2: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); }
5,448,837
//Compatible Solidity Compiler Version pragma solidity ^0.4.25; /* This FulizaLeo Token contract is based on the ERC20 token contract standard. Additional functionality has been integrated: */ contract FulizaLeoToken { string public constant name = "Fuliza Leo Token"; string public constant symbol = "FLT"; uint8 public constant decimals = 18; //database to match user Accounts and their respective balances mapping(address => uint) _balances; mapping(address => mapping( address => uint )) _approvals; //FulizaLeoToken Hard Cap uint public cap_flt; //FulizaLeoToken Current Supply uint public currentSupply; //Authorized FulizaLeoToken Minter Ethereum address address public minter; //check if Account is the Authorized Minter modifier onlyMinter { if (msg.sender != minter) revert(); _; } //check if hard cap is reached before minting new FLT tokens modifier capReached(uint amount) { if((currentSupply + amount) > cap_flt) revert(); _; } event Transfer(address indexed from, address indexed to, uint value ); event Approval(address indexed owner, address indexed spender, uint value ); event TokenMint(address newTokenHolder, uint amountOfTokens); event MinterTransfered(address prevMinter, address nextMinter); //initialize FulizaLeoToken //FulizaLeoToken Constructor Configurations constructor(uint cap_token) public { cap_flt = cap_token; minter = msg.sender; } //retrieve number of all FulizaLeoTokens in existence function totalSupply() public view returns (uint supply) { return currentSupply; } //check FulizaLeoTokens balance of an Ethereum account function balanceOf(address who) public view returns (uint value) { return _balances[who]; } //check how many FulizaLeoTokens a spender is allowed to spend from an owner function allowance(address _owner, address spender) public view returns (uint _allowance) { return _approvals[_owner][spender]; } // A helper to notify if overflow occurs function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a && a + b >= b); } //transfer an amount of FulizaLeoTokens to an Ethereum address 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; } //spend FulizaLeoTokens from another Ethereum account that approves you as spender 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; } //allow another Ethereum account to spend FulizaLeoTokens from your Account function approve(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } //mechanism for FulizaLeoTokens Creation //only minter can create new FulizaLeoTokens //check if FulizaLeoTokens Hard Cap is reached before proceeding - revert if true function mint(address recipient, uint amount) onlyMinter capReached(amount) public returns (bool ok) { if(!safeToAdd(_balances[recipient], amount)) revert(); if(!safeToAdd(currentSupply, amount)) revert(); _balances[recipient] += amount; currentSupply += amount; emit TokenMint(recipient, amount); return true; } //transfer the priviledge of creating new FulizaLeoTokens to another Ethereum account function transferMintership(address newMinter) public onlyMinter returns (bool ok) { minter = newMinter; emit MinterTransfered(minter, newMinter); return true; } }
mechanism for FulizaLeoTokens Creationonly minter can create new FulizaLeoTokenscheck if FulizaLeoTokens Hard Cap is reached before proceeding - revert if true
function mint(address recipient, uint amount) onlyMinter capReached(amount) public returns (bool ok) { if(!safeToAdd(_balances[recipient], amount)) revert(); if(!safeToAdd(currentSupply, amount)) revert(); _balances[recipient] += amount; currentSupply += amount; emit TokenMint(recipient, amount); return true; }
12,977,861
pragma solidity ^0.4.21; import "zeppelin-solidity/contracts/access/rbac/RBAC.sol"; interface ITeamNFT { function _createTeam( uint256 _id, string memory _TeamUrl, string memory _name, address _teamOwner ) public returns (uint256); function mintTeamToken( address teamOwner, string name, string metadata //isTeamOwner(teamOwner) ) public returns (uint256); function evaluateTeam(uint256 teamId, address projectAddress) public; function getTeamCount() public view returns (uint256 teamCount); function transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ); function getTeamById(uint256 teamId) public view returns ( uint256 id, address teamOwner, string name, string TeamUrl, bool exists ); } interface IWeekNFT { /// wrapper on minting new 721 function mint721( address _teamContract, uint256 _teamTokenId, address userAddress ) public returns (uint256); function assignNFTToTeam( address _teamContract, uint256 _teamTokenId, uint256 _weekTokenId, address userAddress ) public; function placeBid( uint256 weekTokenId, address bidder, uint256 price ) public; function transferWeekNFTOnBid( uint256 weekTokenId, address from, address to ); function getWeekById(uint256 weekId) public view returns ( uint256 id, uint256 teamId, address weekOwner, bool exists, string WeekUrl, uint256 price, uint256 WeekNo, uint256 Year ); } contract BundleBond is RBAC { ITeamNFT TEAM; IWeekNFT WEEK; address TeamContractAddress; address weekContractAddress; mapping(address => Admin) AdminList; mapping(address => TeamOwner) TeamOwnerList; mapping(uint256 => Project) projectList; mapping(uint256 => Offer) offerList; uint256 lastProjectId; uint256 lastOfferId; struct Project { string name; address projectAddress; address projectOwner; } struct Offer { uint256 WeekId; address fromAddress; address ownerAddress; bool accepted; } modifier onlyAdmin() { hasRole(msg.sender, "Admin"); _; } modifier onlyTeamOwner() { hasRole(msg.sender, "TEAM_OWNER"); _; } constructor(address _team, address _week) public { TEAM = ITeamNFT(_team); WEEK = IWeekNFT(_week); TeamContractAddress = _team; weekContractAddress = _team; lastProjectId = 0; lastOfferId=0; addRole(msg.sender, "Admin"); } struct Admin { string name; bool exists; } struct TeamOwner { string name; bool exists; } function isAdmin() public returns (bool) { return hasRole(msg.sender, "Admin"); } function addAdmin(string _adminName, address _adminAddress) { Admin storage t = AdminList[_adminAddress]; if (!t.exists) { AdminList[_adminAddress] = Admin({ exists: true, name: _adminName }); addRole(_adminAddress, "Admin"); } } function editAdminName(string _adminName, address _adminAddress) { Admin storage t = AdminList[_adminAddress]; if (t.exists) { AdminList[_adminAddress].name = _adminName; } } function getAdminName(address _adminAddress) view returns (string){ Admin storage admin = AdminList[_adminAddress]; if (admin.exists) { return AdminList[_adminAddress].name; } return ""; } function isTeamOwner() public returns(bool) { return hasRole(msg.sender, "TEAM_OWNER"); } function addTeamOwner(string _teamOwnerName, address _teamOwnerAddress) { TeamOwner storage t = TeamOwnerList[_teamOwnerAddress]; if (!t.exists) { TeamOwnerList[_teamOwnerAddress] = TeamOwner({ exists: true, name: _teamOwnerName }); addRole(_teamOwnerAddress, "TEAM_OWNER"); } } function editTeamOwnerName(string _teamOwnerName, address _teamOwnerAddress) { TeamOwner storage t = TeamOwnerList[_teamOwnerAddress]; if (t.exists) { TeamOwnerList[_teamOwnerAddress].name = _teamOwnerName; } } function getTeamOwnerName(address _teamOwnerAddress) view returns (string){ TeamOwner storage t = TeamOwnerList[_teamOwnerAddress]; if (t.exists) { return TeamOwnerList[_teamOwnerAddress].name; } return ""; } function addTeam( address teamOwner, string teamName, string metadata) returns(uint256) { return TEAM.mintTeamToken(teamOwner, teamName, metadata); } function getTeamCount() public view returns (uint256 teamCount) { return TEAM.getTeamCount(); } function getTeamById(uint256 teamId) public view returns ( uint256 id, address teamOwner, string name, string TeamUrl, bool exists ) { return TEAM.getTeamById(teamId); } function addWeek(uint256 _teamTokenId, address teamOwnerAddress) { WEEK.mint721(TeamContractAddress, _teamTokenId, teamOwnerAddress); } function getWeekById(uint256 weekId) public view returns ( uint256 id, uint256 teamId, address weekOwner, bool exists, string WeekUrl, uint256 price, uint256 WeekNo, uint256 Year ) { return WEEK.getWeekById(weekId); } function purchaseWeekOfTeam( uint256 teamTokenId, uint256 weekTokenId) public payable { //price to team //NFT update (set owner) var ( teamId,teamOwner, name, TeamUrl, teamExists)=getTeamById(teamTokenId); var ( weekId, weekTeamId, weekOwner, weekExists, WeekUrl, price,WeekNo,Year)=getWeekById(teamTokenId); require(msg.value >= (price), "The value is " ); uint256 amountToRefund = msg.value - price; msg.sender.transfer(amountToRefund); weekOwner.transfer(price); sellWeekNFT(teamTokenId, weekTokenId,msg.sender ); } function sellWeekNFT( uint256 teamTokenId, uint256 weekTokenId, address to ) { TEAM.transferChild(teamTokenId, to, weekContractAddress, weekTokenId); } function makeAnOffer( uint256 weekTokenId) public payable { //price to contract //offer map update var ( weekId, teamId, weekOwner, exists, WeekUrl, price,WeekNo,Year)=getWeekById(weekTokenId); require(msg.value >= (price), "The value is " ); uint256 amountToRefund = msg.value - price; msg.sender.transfer(amountToRefund); Offer storage o = offerList[lastOfferId]; offerList[lastOfferId] = Offer({ WeekId:weekTokenId, fromAddress:msg.sender, ownerAddress:weekOwner, accepted:false }); lastOfferId=lastOfferId+1; } function acceptAnOffer(uint256 offerID) public payable { //price to prev owner //change offer status //call transferWeekNFTOnBid var ( weekId, teamId, weekOwner, exists, WeekUrl, price,WeekNo,Year)=getWeekById(offerList[offerID].WeekId); offerList[offerID].ownerAddress.transfer(price); offerList[offerID].accepted = true; transferWeekNFTOnBid( offerList[offerID].WeekId,offerList[offerID].fromAddress, offerList[offerID].ownerAddress ); } function rejectAnOffer(uint256 offerID) public payable { var ( weekId, teamId, weekOwner, exists, WeekUrl, price,WeekNo,Year)=getWeekById(offerList[offerID].WeekId); offerList[offerID].fromTransfer.transfer(price); } function transferWeekNFTOnBid( uint256 weekTokenId, address from, address to ) { WEEK.transferWeekNFTOnBid(weekTokenId,from,to); } function placeBidOnWeekNFT( uint256 weekTokenId, address bidder, uint256 price ) public { WEEK.placeBid(weekTokenId, bidder, price); } function AddProjectToResume(string _name, address _projectAddress) public { projectList[lastProjectId] = Project({ name: _name, projectAddress:_projectAddress, projectOwner:msg.sender }); lastProjectId=lastProjectId+1; } }
price to teamNFT update (set owner)
function purchaseWeekOfTeam( uint256 teamTokenId, uint256 weekTokenId) public payable { var ( teamId,teamOwner, name, TeamUrl, teamExists)=getTeamById(teamTokenId); var ( weekId, weekTeamId, weekOwner, weekExists, WeekUrl, price,WeekNo,Year)=getWeekById(teamTokenId); require(msg.value >= (price), "The value is " ); uint256 amountToRefund = msg.value - price; msg.sender.transfer(amountToRefund); weekOwner.transfer(price); sellWeekNFT(teamTokenId, weekTokenId,msg.sender ); }
6,460,581
/** *Submitted for verification at Etherscan.io on 2021-12-30 */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; ////import './pool/IUniswapV3PoolImmutables.sol'; ////import './pool/IUniswapV3PoolState.sol'; ////import './pool/IUniswapV3PoolDerivedState.sol'; ////import './pool/IUniswapV3PoolActions.sol'; ////import './pool/IUniswapV3PoolOwnerActions.sol'; ////import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.0; ////import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; ////import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; ////import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; ////import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; ////import '../libraries/PoolAddress.sol'; /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Fetches time-weighted average tick using Uniswap V3 oracle /// @param pool Address of Uniswap V3 pool that we want to observe /// @param period Number of seconds in the past to start calculating time-weighted average /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { require(period != 0, 'BP'); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / period); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--; } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; ////import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; ////import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.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); } } } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * ////IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: BUSL-1.1 pragma solidity 0.7.6; interface IICHIVaultFactory { event FeeRecipient( address indexed sender, address feeRecipient); event BaseFee( address indexed sender, uint256 baseFee); event BaseFeeSplit( address indexed sender, uint256 baseFeeSplit); event DeployICHIVaultFactory( address indexed sender, address uniswapV3Factory); event ICHIVaultCreated( address indexed sender, address ichiVault, address tokenA, bool allowTokenA, address tokenB, bool allowTokenB, uint24 fee, uint256 count); function uniswapV3Factory() external view returns(address); function feeRecipient() external view returns(address); function baseFee() external view returns(uint256); function baseFeeSplit() external view returns(uint256); function setFeeRecipient(address _feeRecipient) external; function setBaseFee(uint256 _baseFee) external; function setBaseFeeSplit(uint256 _baseFeeSplit) external; function createICHIVault( address tokenA, bool allowTokenA, address tokenB, bool allowTokenB, uint24 fee ) external returns (address ichiVault); function genKey( address deployer, address token0, address token1, uint24 fee, bool allowToken0, bool allowToken1) external pure returns(bytes32 key); } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: Unlicense pragma solidity 0.7.6; interface IICHIVault{ function ichiVaultFactory() external view returns(address); function pool() external view returns(address); function token0() external view returns(address); function allowToken0() external view returns(bool); function token1() external view returns(address); function allowToken1() external view returns(bool); function fee() external view returns(uint24); function tickSpacing() external view returns(int24); function affiliate() external view returns(address); function baseLower() external view returns(int24); function baseUpper() external view returns(int24); function limitLower() external view returns(int24); function limitUpper() external view returns(int24); function deposit0Max() external view returns(uint256); function deposit1Max() external view returns(uint256); function maxTotalSupply() external view returns(uint256); function hysteresis() external view returns(uint256); function getTotalAmounts() external view returns (uint256, uint256); function deposit( uint256, uint256, address ) external returns (uint256); function withdraw( uint256, address ) external returns (uint256, uint256); function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, int256 swapQuantity ) external; function setDepositMax( uint256 _deposit0Max, uint256 _deposit1Max) external; function setAffiliate( address _affiliate) external; event DeployICHIVault( address indexed sender, address indexed pool, bool allowToken0, bool allowToken1, address owner, uint256 twapPeriod); event SetTwapPeriod( address sender, uint32 newTwapPeriod ); event Deposit( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Withdraw( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Rebalance( int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 feeAmount0, uint256 feeAmount1, uint256 totalSupply ); event MaxTotalSupply( address indexed sender, uint256 maxTotalSupply); event Hysteresis( address indexed sender, uint256 hysteresis); event DepositMax( address indexed sender, uint256 deposit0Max, uint256 deposit1Max); event Affiliate( address indexed sender, address affiliate); } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: BUSL-1.1 pragma solidity 0.7.6; ////import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol"; ////import {LiquidityAmounts} from "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; ////import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol"; library UV3Math { /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /******************* * Tick Math *******************/ function getSqrtRatioAtTick( int24 currentTick ) public pure returns(uint160 sqrtPriceX96) { sqrtPriceX96 = TickMath.getSqrtRatioAtTick(currentTick); } /******************* * LiquidityAmounts *******************/ function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) public pure returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, liquidity); } function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) public pure returns (uint128 liquidity) { liquidity = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1); } /******************* * OracleLibrary *******************/ function consult( address _pool, uint32 _twapPeriod ) public view returns(int24 timeWeightedAverageTick) { timeWeightedAverageTick = OracleLibrary.consult(_pool, _twapPeriod); } function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) public pure returns (uint256 quoteAmount) { quoteAmount = OracleLibrary.getQuoteAtTick(tick, baseAmount, baseToken, quoteToken); } /******************* * SafeUnit128 *******************/ /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) public pure returns (uint128 z) { require((z = uint128(y)) == y, "SafeUint128: overflow"); } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.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 () { 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; } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.0; ////import "./IERC20.sol"; ////import "../../math/SafeMath.sol"; ////import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.7.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_) { _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 { } } /** * SourceUnit: /home/sbadmin/projects/ichi/ichi-vaults/contracts/ICHIVault.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: BUSL-1.1 pragma solidity 0.7.6; ////import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; ////import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; ////import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; ////import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; ////import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; ////import {UV3Math} from "./lib/UV3Math.sol"; ////import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; ////import {IUniswapV3MintCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol"; ////import {IUniswapV3SwapCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol"; ////import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; ////import {IICHIVault} from "../interfaces/IICHIVault.sol"; ////import {IICHIVaultFactory} from "../interfaces/IICHIVaultFactory.sol"; /** @notice A Uniswap V2-like interface with fungible liquidity to Uniswap V3 which allows for either one-sided or two-sided liquidity provision. ICHIVaults should be deployed by the ICHIVaultFactory. ICHIVaults should not be used with tokens that charge transaction fees. */ contract ICHIVault is IICHIVault, IUniswapV3MintCallback, IUniswapV3SwapCallback, ERC20, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; address public immutable override ichiVaultFactory; address public immutable override pool; address public immutable override token0; address public immutable override token1; bool public immutable override allowToken0; bool public immutable override allowToken1; uint24 public immutable override fee; int24 public immutable override tickSpacing; address public override affiliate; int24 public override baseLower; int24 public override baseUpper; int24 public override limitLower; int24 public override limitUpper; // The following three variables serve the very ////important purpose of // limiting inventory risk and the arbitrage opportunities made possible by // instant deposit & withdrawal. // If, in the ETHUSDT pool at an ETH price of 2500 USDT, I deposit 100k // USDT in a pool with 40 WETH, and then directly afterwards withdraw 50k // USDT and 20 WETH (this is of equivalent dollar value), I drastically // change the pool composition and additionally decreases deployed capital // by 50%. Keeping a maxTotalSupply just above our current total supply // means that large amounts of funds can't be deposited all at once to // create a large imbalance of funds or to sideline many funds. // Additionally, deposit maximums prevent users from using the pool as // a counterparty to trade assets against while avoiding uniswap fees // & slippage--if someone were to try to do this with a large amount of // capital they would be overwhelmed by the gas fees necessary to call // deposit & withdrawal many times. uint256 public override deposit0Max; uint256 public override deposit1Max; uint256 public override maxTotalSupply; uint256 public override hysteresis; uint256 public constant PRECISION = 10**18; uint256 constant PERCENT = 100; address constant NULL_ADDRESS = address(0); uint32 public twapPeriod; /** @notice creates an instance of ICHIVault based on the pool. allowToken parameters control whether the ICHIVault allows one-sided or two-sided liquidity provision @param _pool Uniswap V3 pool for which liquidity is managed @param _allowToken0 flag that indicates whether token0 is accepted during deposit @param _allowToken1 flag that indicates whether token1 is accepted during deposit @param __owner Owner of the ICHIVault */ constructor( address _pool, bool _allowToken0, bool _allowToken1, address __owner, uint32 _twapPeriod ) ERC20("ICHI Vault Liquidity", "ICHI_Vault_LP") { require(_pool != NULL_ADDRESS, "IV.constructor: zero address"); require(_allowToken0 || _allowToken1, 'IV.constructor: no allowed tokens'); ichiVaultFactory = msg.sender; pool = _pool; token0 = IUniswapV3Pool(_pool).token0(); token1 = IUniswapV3Pool(_pool).token1(); fee = IUniswapV3Pool(_pool).fee(); allowToken0 = _allowToken0; allowToken1 = _allowToken1; twapPeriod = _twapPeriod; tickSpacing = IUniswapV3Pool(_pool).tickSpacing(); transferOwnership(__owner); maxTotalSupply = 0; // no cap hysteresis = PRECISION.div(PERCENT); // 1% threshold deposit0Max = uint256(-1); // max uint256 deposit1Max = uint256(-1); // max uint256 affiliate = NULL_ADDRESS; // by default there is no affiliate address emit DeployICHIVault( msg.sender, _pool, _allowToken0, _allowToken1, __owner, _twapPeriod ); } function setTwapPeriod(uint32 newTwapPeriod) external onlyOwner { require(newTwapPeriod > 0, "IV.setTwapPeriod: missing period"); twapPeriod = newTwapPeriod; emit SetTwapPeriod(msg.sender, newTwapPeriod); } /** @notice Distributes shares to depositor equal to the token1 value of his deposit multiplied by the ratio of total liquidity shares issued divided by the pool's AUM measured in token1 value. @param deposit0 Amount of token0 transfered from sender to ICHIVault @param deposit1 Amount of token0 transfered from sender to ICHIVault @param to Address to which liquidity tokens are minted @param shares Quantity of liquidity tokens minted as a result of deposit */ function deposit( uint256 deposit0, uint256 deposit1, address to ) external override nonReentrant returns (uint256 shares) { require(allowToken0 || deposit0 == 0, "IV.deposit: token0 not allowed"); require(allowToken1 || deposit1 == 0, "IV.deposit: token1 not allowed"); require( deposit0 > 0 || deposit1 > 0, "IV.deposit: deposits must be > 0" ); require( deposit0 < deposit0Max && deposit1 < deposit1Max, "IV.deposit: deposits too large" ); require(to != NULL_ADDRESS && to != address(this), "IV.deposit: to"); // update fees for inclusion in total pool amounts (uint128 baseLiquidity, , ) = _position(baseLower, baseUpper); if (baseLiquidity > 0) { (uint burn0, uint burn1) = IUniswapV3Pool(pool).burn(baseLower, baseUpper, 0); require(burn0 == 0 && burn1 == 0, "IV.deposit: unexpected burn (1)"); } (uint128 limitLiquidity, , ) = _position(limitLower, limitUpper); if (limitLiquidity > 0) { (uint burn0, uint burn1) = IUniswapV3Pool(pool).burn(limitLower, limitUpper, 0); require(burn0 == 0 && burn1 == 0, "IV.deposit: unexpected burn (2)"); } // Spot uint256 price = _fetchSpot( token0, token1, currentTick(), PRECISION ); // TWAP uint256 twap = _fetchTwap( pool, token0, token1, twapPeriod, PRECISION); // if difference between spot and twap is too big, check if the price may have been manipulated in this block uint256 delta = (price > twap) ? price.sub(twap).mul(PRECISION).div(price) : twap.sub(price).mul(PRECISION).div(twap); if (delta > hysteresis) require(checkHysteresis(), "IV.deposit: try later"); (uint256 pool0, uint256 pool1) = getTotalAmounts(); // aggregated deposit uint256 deposit0PricedInToken1 = deposit0.mul((price < twap) ? price : twap).div(PRECISION); if (deposit0 > 0) { IERC20(token0).safeTransferFrom( msg.sender, address(this), deposit0 ); } if (deposit1 > 0) { IERC20(token1).safeTransferFrom( msg.sender, address(this), deposit1 ); } shares = deposit1.add(deposit0PricedInToken1); if (totalSupply() != 0) { uint256 pool0PricedInToken1 = pool0.mul((price > twap) ? price : twap).div(PRECISION); shares = shares.mul(totalSupply()).div( pool0PricedInToken1.add(pool1) ); } _mint(to, shares); emit Deposit(msg.sender, to, shares, deposit0, deposit1); // Check total supply cap not exceeded. A value of 0 means no limit. require( maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "IV.deposit: maxTotalSupply" ); } /** @notice Redeems shares by sending out a percentage of the ICHIVault's AUM - this percentage is equal to the percentage of total issued shares represented by the redeeemed shares. @param shares Number of liquidity tokens to redeem as pool assets @param to Address to which redeemed pool assets are sent @param amount0 Amount of token0 redeemed by the submitted liquidity tokens @param amount1 Amount of token1 redeemed by the submitted liquidity tokens */ function withdraw(uint256 shares, address to) external override nonReentrant returns (uint256 amount0, uint256 amount1) { require(shares > 0, "IV.withdraw: shares"); require(to != NULL_ADDRESS, "IV.withdraw: to"); // Withdraw liquidity from Uniswap pool (uint256 base0, uint256 base1) = _burnLiquidity( baseLower, baseUpper, _liquidityForShares(baseLower, baseUpper, shares), to, false ); (uint256 limit0, uint256 limit1) = _burnLiquidity( limitLower, limitUpper, _liquidityForShares(limitLower, limitUpper, shares), to, false ); // Push tokens proportional to unused balances uint256 _totalSupply = totalSupply(); uint256 unusedAmount0 = IERC20(token0) .balanceOf(address(this)) .mul(shares) .div(_totalSupply); uint256 unusedAmount1 = IERC20(token1) .balanceOf(address(this)) .mul(shares) .div(_totalSupply); if (unusedAmount0 > 0) IERC20(token0).safeTransfer(to, unusedAmount0); if (unusedAmount1 > 0) IERC20(token1).safeTransfer(to, unusedAmount1); amount0 = base0.add(limit0).add(unusedAmount0); amount1 = base1.add(limit1).add(unusedAmount1); _burn(msg.sender, shares); emit Withdraw(msg.sender, to, shares, amount0, amount1); } /** @notice Updates ICHIVault's LP positions. @dev The base position is placed first with as much liquidity as possible and is typically symmetric around the current price. This order should use up all of one token, leaving some unused quantity of the other. This unused amount is then placed as a single-sided order. @param _baseLower The lower tick of the base position @param _baseUpper The upper tick of the base position @param _limitLower The lower tick of the limit position @param _limitUpper The upper tick of the limit position @param swapQuantity Quantity of tokens to swap; if quantity is positive, `swapQuantity` token0 are swaped for token1, if negative, `swapQuantity` token1 is swaped for token0 */ function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, int256 swapQuantity ) external override nonReentrant onlyOwner { require( _baseLower < _baseUpper && _baseLower % tickSpacing == 0 && _baseUpper % tickSpacing == 0, "IV.rebalance: base position invalid" ); require( _limitLower < _limitUpper && _limitLower % tickSpacing == 0 && _limitUpper % tickSpacing == 0, "IV.rebalance: limit position invalid" ); // update fees (uint128 baseLiquidity, , ) = _position(baseLower, baseUpper); if (baseLiquidity > 0) { IUniswapV3Pool(pool).burn(baseLower, baseUpper, 0); } (uint128 limitLiquidity, , ) = _position(limitLower, limitUpper); if (limitLiquidity > 0) { IUniswapV3Pool(pool).burn(limitLower, limitUpper, 0); } // Withdraw all liquidity and collect all fees from Uniswap pool (, uint256 feesBase0, uint256 feesBase1) = _position( baseLower, baseUpper ); (, uint256 feesLimit0, uint256 feesLimit1) = _position( limitLower, limitUpper ); uint256 fees0 = feesBase0.add(feesLimit0); uint256 fees1 = feesBase1.add(feesLimit1); _burnLiquidity( baseLower, baseUpper, baseLiquidity, address(this), true ); _burnLiquidity( limitLower, limitUpper, limitLiquidity, address(this), true ); _distributeFees(fees0, fees1); emit Rebalance( currentTick(), IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), fees0, fees1, totalSupply() ); // swap tokens if required if (swapQuantity != 0) { IUniswapV3Pool(pool).swap( address(this), swapQuantity > 0, swapQuantity > 0 ? swapQuantity : -swapQuantity, swapQuantity > 0 ? UV3Math.MIN_SQRT_RATIO + 1 : UV3Math.MAX_SQRT_RATIO - 1, abi.encode(address(this)) ); } baseLower = _baseLower; baseUpper = _baseUpper; baseLiquidity = _liquidityForAmounts( baseLower, baseUpper, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)) ); _mintLiquidity(baseLower, baseUpper, baseLiquidity); limitLower = _limitLower; limitUpper = _limitUpper; limitLiquidity = _liquidityForAmounts( limitLower, limitUpper, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)) ); _mintLiquidity(limitLower, limitUpper, limitLiquidity); } /** @notice Sends portion of swap fees to feeRecipient and affiliate. @param fees0 fees for token0 @param fees1 fees for token1 */ function _distributeFees(uint256 fees0, uint256 fees1) internal { uint256 baseFee = IICHIVaultFactory(ichiVaultFactory).baseFee(); // if there is no affiliate 100% of the baseFee should go to feeRecipient uint256 baseFeeSplit = (affiliate == NULL_ADDRESS) ? PRECISION : IICHIVaultFactory(ichiVaultFactory).baseFeeSplit(); address feeRecipient = IICHIVaultFactory(ichiVaultFactory).feeRecipient(); require(baseFee <= PRECISION, "IV.rebalance: fee must be <= 10**18"); require(baseFeeSplit <= PRECISION, "IV.rebalance: split must be <= 10**18"); require(feeRecipient != NULL_ADDRESS, "IV.rebalance: zero address"); if (baseFee > 0) { if (fees0 > 0) { uint256 totalFee = fees0.mul(baseFee).div(PRECISION); uint256 toRecipient = totalFee.mul(baseFeeSplit).div(PRECISION); uint256 toAffiliate = totalFee.sub(toRecipient); IERC20(token0).safeTransfer(feeRecipient, toRecipient); if (toAffiliate > 0) { IERC20(token0).safeTransfer(affiliate, toAffiliate); } } if (fees1 > 0) { uint256 totalFee = fees1.mul(baseFee).div(PRECISION); uint256 toRecipient = totalFee.mul(baseFeeSplit).div(PRECISION); uint256 toAffiliate = totalFee.sub(toRecipient); IERC20(token1).safeTransfer(feeRecipient, toRecipient); if (toAffiliate > 0) { IERC20(token1).safeTransfer(affiliate, toAffiliate); } } } } /** @notice Mint liquidity in Uniswap V3 pool. @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param liquidity Amount of liquidity to mint @param amount0 Used amount of token0 @param amount1 Used amount of token1 */ function _mintLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal returns (uint256 amount0, uint256 amount1) { if (liquidity > 0) { (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), tickLower, tickUpper, liquidity, abi.encode(address(this)) ); } } /** @notice Burn liquidity in Uniswap V3 pool. @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param liquidity amount of liquidity to burn @param to The account to receive token0 and token1 amounts @param collectAll Flag that indicates whether all token0 and token1 tokens should be collected or only the ones released during this burn @param amount0 released amount of token0 @param amount1 released amount of token1 */ function _burnLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity, address to, bool collectAll ) internal returns (uint256 amount0, uint256 amount1) { if (liquidity > 0) { // Burn liquidity (uint256 owed0, uint256 owed1) = IUniswapV3Pool(pool).burn( tickLower, tickUpper, liquidity ); // Collect amount owed uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0); uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1); if (collect0 > 0 || collect1 > 0) { (amount0, amount1) = IUniswapV3Pool(pool).collect( to, tickLower, tickUpper, collect0, collect1 ); } } } /** @notice Calculates liquidity amount for the given shares. @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param shares number of shares */ function _liquidityForShares( int24 tickLower, int24 tickUpper, uint256 shares ) internal view returns (uint128) { (uint128 position, , ) = _position(tickLower, tickUpper); return _uint128Safe(uint256(position).mul(shares).div(totalSupply())); } /** @notice Returns information about the liquidity position. @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param liquidity liquidity amount @param tokensOwed0 amount of token0 owed to the owner of the position @param tokensOwed1 amount of token1 owed to the owner of the position */ function _position(int24 tickLower, int24 tickUpper) internal view returns ( uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) { bytes32 positionKey = keccak256( abi.encodePacked(address(this), tickLower, tickUpper) ); (liquidity, , , tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool) .positions(positionKey); } /** @notice Callback function for mint @dev this is where the payer transfers required token0 and token1 amounts @param amount0 required amount of token0 @param amount1 required amount of token1 @param data encoded payer's address */ function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external override { require(msg.sender == address(pool), "cb1"); address payer = abi.decode(data, (address)); if (payer == address(this)) { if (amount0 > 0) IERC20(token0).safeTransfer(msg.sender, amount0); if (amount1 > 0) IERC20(token1).safeTransfer(msg.sender, amount1); } else { if (amount0 > 0) IERC20(token0).safeTransferFrom(payer, msg.sender, amount0); if (amount1 > 0) IERC20(token1).safeTransferFrom(payer, msg.sender, amount1); } } /** @notice Callback function for swap @dev this is where the payer transfers required token0 and token1 amounts @param amount0Delta required amount of token0 @param amount1Delta required amount of token1 @param data encoded payer's address */ function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external override { require(msg.sender == address(pool), "cb2"); address payer = abi.decode(data, (address)); if (amount0Delta > 0) { if (payer == address(this)) { IERC20(token0).safeTransfer(msg.sender, uint256(amount0Delta)); } else { IERC20(token0).safeTransferFrom( payer, msg.sender, uint256(amount0Delta) ); } } else if (amount1Delta > 0) { if (payer == address(this)) { IERC20(token1).safeTransfer(msg.sender, uint256(amount1Delta)); } else { IERC20(token1).safeTransferFrom( payer, msg.sender, uint256(amount1Delta) ); } } } /** @notice Checks if the last price change happened in the current block */ function checkHysteresis() private view returns(bool) { (, , uint16 observationIndex, , , , ) = IUniswapV3Pool(pool).slot0(); (uint32 blockTimestamp, , ,) = IUniswapV3Pool(pool).observations(observationIndex); return( block.timestamp != blockTimestamp ); } /** @notice Sets the maximum liquidity token supply the contract allows @dev onlyOwner @param _maxTotalSupply The maximum liquidity token supply the contract allows */ function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner { maxTotalSupply = _maxTotalSupply; emit MaxTotalSupply(msg.sender, _maxTotalSupply); } /** @notice Sets the hysteresis threshold (in percentage points, 10**16 = 1%). When difference between spot price and TWAP exceeds the threshold, a check for a flashloan attack is executed @dev onlyOwner @param _hysteresis hysteresis threshold */ function setHysteresis(uint256 _hysteresis) external onlyOwner { hysteresis = _hysteresis; emit Hysteresis(msg.sender, _hysteresis); } /** @notice Sets the affiliate account address where portion of the collected swap fees will be distributed @dev onlyOwner @param _affiliate The affiliate account address */ function setAffiliate(address _affiliate) external override onlyOwner { affiliate = _affiliate; emit Affiliate(msg.sender, _affiliate); } /** @notice Sets the maximum token0 and token1 amounts the contract allows in a deposit @dev onlyOwner @param _deposit0Max The maximum amount of token0 allowed in a deposit @param _deposit1Max The maximum amount of token1 allowed in a deposit */ function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external override onlyOwner { deposit0Max = _deposit0Max; deposit1Max = _deposit1Max; emit DepositMax(msg.sender, _deposit0Max, _deposit1Max); } /** @notice Calculates token0 and token1 amounts for liquidity in a position @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param liquidity Amount of liquidity in the position */ function _amountsForLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256, uint256) { (uint160 sqrtRatioX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); return UV3Math.getAmountsForLiquidity( sqrtRatioX96, UV3Math.getSqrtRatioAtTick(tickLower), UV3Math.getSqrtRatioAtTick(tickUpper), liquidity ); } /** @notice Calculates amount of liquidity in a position for given token0 and token1 amounts @param tickLower The lower tick of the liquidity position @param tickUpper The upper tick of the liquidity position @param amount0 token0 amount @param amount1 token1 amount */ function _liquidityForAmounts( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ) internal view returns (uint128) { (uint160 sqrtRatioX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); return UV3Math.getLiquidityForAmounts( sqrtRatioX96, UV3Math.getSqrtRatioAtTick(tickLower), UV3Math.getSqrtRatioAtTick(tickUpper), amount0, amount1 ); } /** @notice uint128Safe function @param x input value */ function _uint128Safe(uint256 x) internal pure returns (uint128) { require(x <= type(uint128).max, "IV.128_OF"); return uint128(x); } /** @notice Calculates total quantity of token0 and token1 in both positions (and unused in the ICHIVault) @param total0 Quantity of token0 in both positions (and unused in the ICHIVault) @param total1 Quantity of token1 in both positions (and unused in the ICHIVault) */ function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) { (, uint256 base0, uint256 base1) = getBasePosition(); (, uint256 limit0, uint256 limit1) = getLimitPosition(); total0 = IERC20(token0).balanceOf(address(this)).add(base0).add(limit0); total1 = IERC20(token1).balanceOf(address(this)).add(base1).add(limit1); } /** @notice Calculates amount of total liquidity in the base position @param liquidity Amount of total liquidity in the base position @param amount0 Estimated amount of token0 that could be collected by burning the base position @param amount1 Estimated amount of token1 that could be collected by burning the base position */ function getBasePosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { ( uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) = _position(baseLower, baseUpper); (amount0, amount1) = _amountsForLiquidity( baseLower, baseUpper, positionLiquidity ); liquidity = positionLiquidity; amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); } /** @notice Calculates amount of total liquidity in the limit position @param liquidity Amount of total liquidity in the base position @param amount0 Estimated amount of token0 that could be collected by burning the limit position @param amount1 Estimated amount of token1 that could be collected by burning the limit position */ function getLimitPosition() public view returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { ( uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) = _position(limitLower, limitUpper); (amount0, amount1) = _amountsForLiquidity( limitLower, limitUpper, positionLiquidity ); liquidity = positionLiquidity; amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1)); } /** @notice Returns current price tick @param tick Uniswap pool's current price tick */ function currentTick() public view returns (int24 tick) { (, int24 tick_, , , , , bool unlocked_) = IUniswapV3Pool(pool).slot0(); require(unlocked_, "IV.currentTick: the pool is locked"); tick = tick_; } /** @notice returns equivalent _tokenOut for _amountIn, _tokenIn using spot price @param _tokenIn token the input amount is in @param _tokenOut token for the output amount @param _tick tick for the spot price @param _amountIn amount in _tokenIn @param amountOut equivalent anount in _tokenOut */ function _fetchSpot( address _tokenIn, address _tokenOut, int24 _tick, uint256 _amountIn ) internal pure returns (uint256 amountOut) { return UV3Math.getQuoteAtTick( _tick, UV3Math.toUint128(_amountIn), _tokenIn, _tokenOut ); } /** @notice returns equivalent _tokenOut for _amountIn, _tokenIn using TWAP price @param _pool Uniswap V3 pool address to be used for price checking @param _tokenIn token the input amount is in @param _tokenOut token for the output amount @param _twapPeriod the averaging time period @param _amountIn amount in _tokenIn @param amountOut equivalent anount in _tokenOut */ function _fetchTwap( address _pool, address _tokenIn, address _tokenOut, uint32 _twapPeriod, uint256 _amountIn ) internal view returns (uint256 amountOut) { // Leave twapTick as a int256 to avoid solidity casting int256 twapTick = UV3Math.consult(_pool, _twapPeriod); return UV3Math.getQuoteAtTick( int24(twapTick), // can assume safe being result from consult() UV3Math.toUint128(_amountIn), _tokenIn, _tokenOut ); } }
Permissionless pool actions Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions { function initialize(uint160 sqrtPriceX96) external; function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } pragma solidity >=0.5.0; }
15,255,405
pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../token/IERC20MintableDetailed.sol"; import "../state/StateMachine.sol"; import "../math/DecimalMath.sol"; /** * @title Issuance * @notice Implements a very simple issuance process for tokens * * 1. Initialize contract with the issuance token contract address. This address must inherit from `ERC20Mintable` and `ERC20Detailed`. * 2. Use `setIssuePrice` to determine how many ether (in wei) do investors * have to pay for each issued token. * 3. Use `startIssuance` to allow investors to invest. * 4. Investors can `invest` their ether at will. * 5. Investors can also `cancelInvestment` and get their ether back. * 6. The contract owner can `cancelAllInvestments` to close the investment phase. * In this case `invest` is not available, but `cancelInvestment` is. * 7. Use `startDistribution` to close the investment phase. * 8. Investors can only `claim` their issued tokens now. * 9. Owner can use `withdraw` to send collected ether to a wallet. */ contract IssuanceEth is Ownable, StateMachine, ReentrancyGuard { using SafeMath for uint256; using DecimalMath for uint256; event IssuanceCreated(); event IssuePriceSet(); event InvestmentAdded(address investor, uint256 amount); event InvestmentCancelled(address investor, uint256 amount); address public issuanceToken; address[] public investors; mapping(address => uint256) public investments; uint256 public amountRaised; uint256 public amountWithdrawn; uint256 public issuePrice; constructor( address _issuanceToken ) public Ownable() StateMachine() { issuanceToken = _issuanceToken; _createTransition("SETUP", "OPEN"); _createTransition("OPEN", "LIVE"); _createTransition("OPEN", "FAILED"); emit IssuanceCreated(); } /** * @notice Use this function to claim your issuance tokens * @dev Each user will call this function on his behalf */ function claim() external virtual nonReentrant { require( currentState == "LIVE", "Cannot claim now." ); require( investments[msg.sender] > 0, "No investments found." ); uint256 amount = investments[msg.sender]; investments[msg.sender] = 0; IERC20MintableDetailed _issuanceToken = IERC20MintableDetailed( issuanceToken ); _issuanceToken.mint( msg.sender, amount.divd(issuePrice, _issuanceToken.decimals()) ); } /** * @dev Function for an investor to cancel his investment */ function cancelInvestment() external virtual nonReentrant { require ( currentState == "OPEN" || currentState == "FAILED", "Cannot cancel now." ); require( investments[msg.sender] > 0, "No investments found." ); uint256 amount = investments[msg.sender]; investments[msg.sender] = 0; msg.sender.transfer(amount); emit InvestmentCancelled(msg.sender, amount); } /** * @notice Invest into the issuance by sending ether to this function */ function invest() public virtual payable { require( currentState == "OPEN", "Not open for investments." ); require( msg.value.mod(issuePrice) == 0, "Fractional investments not allowed." ); if (investments[msg.sender] == 0){ investors.push(msg.sender); } investments[msg.sender] = investments[msg.sender].add(msg.value); amountRaised = amountRaised.add(msg.value); emit InvestmentAdded(msg.sender, msg.value); } /** * @dev Function to open the issuance to investors */ function startIssuance() public virtual onlyOwner { require( issuePrice > 0, "Issue price not set." ); _transition("OPEN"); } /** * @dev Function to move to the distributing phase */ function startDistribution() public virtual onlyOwner { _transition("LIVE"); } /** * @dev Function to cancel all investments */ function cancelAllInvestments() public virtual onlyOwner{ _transition("FAILED"); } /** * @dev Function to transfer all collected tokens to the wallet of the owner */ function withdraw(address payable _wallet) public virtual onlyOwner nonReentrant { require( currentState == "LIVE", "Cannot withdraw funds now." ); uint256 amount = amountRaised - amountWithdrawn; amountWithdrawn = amount; _wallet.transfer(amount); } function setIssuePrice(uint256 _issuePrice) public virtual onlyOwner { require( currentState == "SETUP", "Cannot setup now." ); issuePrice = _issuePrice; emit IssuePriceSet(); } }
Function to move to the distributing phase/
function startDistribution() public virtual onlyOwner { _transition("LIVE"); }
12,907,323
./full_match/1/0xe86F00192b5e2849104bcc5280a169c654418918/sources/contracts/MetaGreys.sol
require(isSaleActive, "Sale is currently not active");require(MAX_TOKENS > _tokenIdCounter.current() + 1, "Not enough tokens left to buy.");require(msg.value >= FEE, "Value below price");_setTokenURI(_tokenIdCounter.current(), tokenURI_);_tokenIdCounter.increment();
function safeMintTo(address _to, uint tokenid) public onlyOwner { _safeMint(_to, tokenid); }
2,941,472
pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } pragma solidity ^0.6.0; import "../interfaces/GasTokenInterface.sol"; contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } pragma solidity ^0.6.0; abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } pragma solidity ^0.6.0; abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsStable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } pragma solidity ^0.6.0; /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } pragma solidity ^0.6.0; import "../interfaces/ERC20.sol"; import "./Address.sol"; import "./SafeMath.sol"; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } pragma solidity ^0.6.0; interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } pragma solidity ^0.6.0; library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.6.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; import "../interfaces/DSProxyInterface.sol"; import "./SafeERC20.sol"; /// @title Pulls a specified amount of tokens from the EOA owner account to the proxy contract PullTokensProxy { using SafeERC20 for ERC20; /// @notice Pulls a token from the proxyOwner -> proxy /// @dev Proxy owner must first give approve to the proxy address /// @param _tokenAddr Address of the ERC20 token /// @param _amount Amount of tokens which will be transfered to the proxy function pullTokens(address _tokenAddr, uint _amount) public { address proxyOwner = DSProxyInterface(address(this)).owner(); ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount); } } pragma solidity ^0.6.0; abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } pragma solidity ^0.6.0; import "../auth/Auth.sol"; import "../interfaces/DSProxyInterface.sol"; // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } pragma solidity ^0.6.0; import "./AdminAuth.sol"; contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmin() { require(admin == msg.sender); _; } constructor() public { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/ILendingPool.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/ILoanShifter.sol"; import "../interfaces/DSProxyInterface.sol"; import "../interfaces/Vat.sol"; import "../interfaces/Manager.sol"; import "../interfaces/IMCDSubscriptions.sol"; import "../interfaces/ICompoundSubscriptions.sol"; import "../auth/AdminAuth.sol"; import "../auth/ProxyPermission.sol"; import "../exchangeV3/DFSExchangeData.sol"; import "./ShifterRegistry.sol"; import "../utils/GasBurner.sol"; import "../loggers/DefisaverLogger.sol"; /// @title LoanShifterTaker Entry point for using the shifting operation contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } // encode data bytes memory paramsData = abi.encode(_loanShift, _exchangeData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return getUnderlyingAddr(_address); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function logEvent( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } pragma solidity ^0.6.0; abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } pragma solidity ^0.6.0; abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } pragma solidity ^0.6.0; abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } pragma solidity ^0.6.0; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } pragma solidity ^0.6.0; abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } pragma solidity ^0.6.0; import "../DS/DSGuard.sol"; import "../DS/DSAuth.sol"; contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract DFSExchangeData { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address wrapper; address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; } struct ExchangeData { address srcAddr; address destAddr; uint256 srcAmount; uint256 destAmount; uint256 minPrice; uint256 dfsFeeDivider; // service fee divider address user; // user to check special fee address wrapper; bytes wrapperData; OffchainData offchainData; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { return abi.encode(_exData); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { _exData = abi.decode(_data, (ExchangeData)); } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } pragma solidity ^0.6.0; contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } pragma solidity ^0.6.0; abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } pragma solidity ^0.6.0; import "./DSAuthority.sol"; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } pragma solidity ^0.6.0; abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../loggers/DefisaverLogger.sol"; import "../../utils/Discount.sol"; import "../../interfaces/reflexer/IOracleRelayer.sol"; import "../../interfaces/reflexer/ITaxCollector.sol"; import "../../interfaces/reflexer/ICoinJoin.sol"; import "./RAISaverProxyHelper.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Implements Boost and Repay for Reflexer Safes contract RAISaverProxy is DFSExchangeCore, RAISaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_COLL_TYPE = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant RAI_JOIN_ADDRESS = 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; address public constant RAI_ADDRESS = 0x03ab458634910AaD20eF5f1C8ee96F1D6ac54919; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; ISAFEEngine public constant safeEngine = ISAFEEngine(SAFE_ENGINE_ADDRESS); ICoinJoin public constant raiJoin = ICoinJoin(RAI_JOIN_ADDRESS); IOracleRelayer public constant oracleRelayer = IOracleRelayer(ORACLE_RELAYER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Rai and repays the debt /// @dev Must be called by the DSProxy contract that owns the Safe function repay( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); drawCollateral(managerAddr, _safeId, _joinAddr, _exchangeData.srcAmount, true); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint raiAmount) = _sell(_exchangeData); raiAmount -= takeFee(_gasCost, raiAmount); paybackDebt(managerAddr, _safeId, ilk, raiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIRepay", abi.encode(_safeId, user, _exchangeData.srcAmount, raiAmount)); } /// @notice Boost - draws Rai, converts to collateral and adds to Safe /// @dev Must be called by the DSProxy contract that owns the Safe function boost( ExchangeData memory _exchangeData, uint _safeId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(ISAFEManager(managerAddr), _safeId); bytes32 ilk = ISAFEManager(managerAddr).collateralTypes(_safeId); uint raiDrawn = drawRai(managerAddr, _safeId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = raiDrawn - takeFee(_gasCost, raiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _safeId, _joinAddr, swapedColl, true); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "RAIBoost", abi.encode(_safeId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Rai from the Safe /// @dev If _raiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to draw function drawRai(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount) internal returns (uint) { uint rate = ITaxCollector(TAX_COLLECTOR_ADDRESS).taxSingle(_collType); uint raiVatBalance = safeEngine.coinBalance(ISAFEManager(_managerAddr).safes(_safeId)); uint maxAmount = getMaxDebt(_managerAddr, _safeId, _collType); if (_raiAmount >= maxAmount) { _raiAmount = sub(maxAmount, 1); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, int(0), normalizeDrawAmount(_raiAmount, rate, raiVatBalance)); ISAFEManager(_managerAddr).transferInternalCoins(_safeId, address(this), toRad(_raiAmount)); if (safeEngine.safeRights(address(this), address(RAI_JOIN_ADDRESS)) == 0) { safeEngine.approveSAFEModification(RAI_JOIN_ADDRESS); } ICoinJoin(RAI_JOIN_ADDRESS).exit(address(this), _raiAmount); return _raiAmount; } /// @notice Adds collateral to the Safe /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to add /// @param _toWeth Should we convert to Weth function addCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toWeth) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr) && _toWeth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(IBasicTokenAdapters(_joinAddr).collateral())).safeApprove(_joinAddr, _amount); IBasicTokenAdapters(_joinAddr).join(address(this), _amount); safeEngine.modifySAFECollateralization( ISAFEManager(_managerAddr).collateralTypes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the Safe Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _safeId Id of the Safe /// @param _joinAddr Address of the join contract for the Safe collateral /// @param _amount Amount of collateral to draw /// @param _toEth Boolean if we should unwrap Ether function drawCollateral(address _managerAddr, uint _safeId, address _joinAddr, uint _amount, bool _toEth) internal returns (uint) { uint frobAmount = _amount; if (IBasicTokenAdapters(_joinAddr).decimals() != 18) { frobAmount = _amount * (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, -toPositiveInt(frobAmount), 0); ISAFEManager(_managerAddr).transferCollateral(_safeId, address(this), frobAmount); IBasicTokenAdapters(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr) && _toEth) { TokenInterface(IBasicTokenAdapters(_joinAddr).collateral()).withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Rai debt /// @param _managerAddr Address of the Safe Manager /// @dev If the _raiAmount is bigger than the whole debt, returns extra Rai /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _raiAmount Amount of Rai to payback /// @param _owner Address that owns the DSProxy that owns the Safe function paybackDebt(address _managerAddr, uint _safeId, bytes32 _collType, uint _raiAmount, address _owner) internal { address urn = ISAFEManager(_managerAddr).safes(_safeId); uint wholeDebt = getAllDebt(SAFE_ENGINE_ADDRESS, urn, urn, _collType); if (_raiAmount > wholeDebt) { ERC20(RAI_ADDRESS).transfer(_owner, sub(_raiAmount, wholeDebt)); _raiAmount = wholeDebt; } if (ERC20(RAI_ADDRESS).allowance(address(this), RAI_JOIN_ADDRESS) == 0) { ERC20(RAI_ADDRESS).approve(RAI_JOIN_ADDRESS, uint(-1)); } raiJoin.join(urn, _raiAmount); int paybackAmnt = _getRepaidDeltaDebt(SAFE_ENGINE_ADDRESS, ISAFEEngine(safeEngine).coinBalance(urn), urn, _collType); ISAFEManager(_managerAddr).modifySAFECollateralization(_safeId, 0, paybackAmnt); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @param _joinAddr Joind address of collateral /// @dev Substracts 1% to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _safeId, bytes32 _collType, address _joinAddr) public view returns (uint) { (uint collateral, uint debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint maxCollateral = sub(collateral, wmul(wdiv(RAY, safetyPrice), debt)); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the Safe Manager /// @param _safeId Id of the Safe /// @param _collType Coll type of the Safe /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public view virtual returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(sub(rmul(collateral, safetyPrice), debt), 10); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethRaiPrice = getPrice(ETH_COLL_TYPE); uint feeAmount = rmul(_gasCost, ethRaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(RAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } } pragma solidity ^0.6.0; contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } pragma solidity ^0.6.0; abstract contract IOracleRelayer { struct CollateralType { address orcl; uint256 safetyCRatio; } mapping (bytes32 => CollateralType) public collateralTypes; function redemptionPrice() public virtual returns (uint256); uint256 public redemptionRate; } pragma solidity ^0.6.0; abstract contract ITaxCollector { struct CollateralType { uint256 stabilityFee; uint256 updateTime; } mapping (bytes32 => CollateralType) public collateralTypes; function taxSingle(bytes32) public virtual returns (uint); } pragma solidity ^0.6.0; abstract contract ICoinJoin { uint256 public decimals; function join(address account, uint256 wad) external virtual; function exit(address account, uint256 wad) external virtual; } pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../interfaces/reflexer/IBasicTokenAdapters.sol"; import "../../interfaces/reflexer/ISAFEManager.sol"; import "../../interfaces/reflexer/ISAFEEngine.sol"; import "../../interfaces/reflexer/ITaxCollector.sol"; /// @title Helper methods for RAISaverProxy contract RAISaverProxyHelper is DSMath { enum ManagerType { RAI } /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that Safe function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - IBasicTokenAdapters(_joinAddr).decimals())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Safe /// @param _safeEngine Address of Vat contract /// @param _urn Urn of the Safe /// @param _collType CollType of the Safe function normalizePaybackAmount(address _safeEngine, address _urn, bytes32 _collType) internal view returns (int amount) { uint dai = ISAFEEngine(_safeEngine).coinBalance(_urn); (, uint rate,,,,) = ISAFEEngine(_safeEngine).collateralTypes(_collType); (, uint art) = ISAFEEngine(_safeEngine).safes(_collType, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets delta debt generated (Total Safe debt minus available safeHandler COIN balance) /// @param safeEngine address /// @param taxCollector address /// @param safeHandler address /// @param collateralType bytes32 /// @return deltaDebt function _getGeneratedDeltaDebt( address safeEngine, address taxCollector, address safeHandler, bytes32 collateralType, uint wad ) internal returns (int deltaDebt) { // Updates stability fee rate uint rate = ITaxCollector(taxCollector).taxSingle(collateralType); require(rate > 0, "invalid-collateral-type"); // Gets COIN balance of the handler in the safeEngine uint coin = ISAFEEngine(safeEngine).coinBalance(safeHandler); // If there was already enough COIN in the safeEngine balance, just exits it without adding more debt if (coin < mul(wad, RAY)) { // Calculates the needed deltaDebt so together with the existing coins in the safeEngine is enough to exit wad amount of COIN tokens deltaDebt = toPositiveInt(sub(mul(wad, RAY), coin) / rate); // This is neeeded due lack of precision. It might need to sum an extra deltaDebt wei (for the given COIN wad amount) deltaDebt = mul(uint(deltaDebt), rate) < mul(wad, RAY) ? deltaDebt + 1 : deltaDebt; } } function _getRepaidDeltaDebt( address safeEngine, uint coin, address safe, bytes32 collateralType ) internal view returns (int deltaDebt) { // Gets actual rate from the safeEngine (, uint rate,,,,) = ISAFEEngine(safeEngine).collateralTypes(collateralType); require(rate > 0, "invalid-collateral-type"); // Gets actual generatedDebt value of the safe (, uint generatedDebt) = ISAFEEngine(safeEngine).safes(collateralType, safe); // Uses the whole coin balance in the safeEngine to reduce the debt deltaDebt = toPositiveInt(coin / rate); // Checks the calculated deltaDebt is not higher than safe.generatedDebt (total debt), otherwise uses its value deltaDebt = uint(deltaDebt) <= generatedDebt ? - deltaDebt : - toPositiveInt(generatedDebt); } /// @notice Gets the whole debt of the Safe /// @param _safeEngine Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Safe /// @param _collType CollType of the Safe function getAllDebt(address _safeEngine, address _usr, address _urn, bytes32 _collType) internal view returns (uint daiAmount) { (, uint rate,,,,) = ISAFEEngine(_safeEngine).collateralTypes(_collType); (, uint art) = ISAFEEngine(_safeEngine).safes(_collType, _urn); uint dai = ISAFEEngine(_safeEngine).coinBalance(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(IBasicTokenAdapters(_joinAddr).collateral()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x0A5653CCa4DB1B6E265F47CAf6969e64f1CFdC45) return false; // if coll is weth it's and eth type coll if (address(IBasicTokenAdapters(_joinAddr).collateral()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets Safe info (collateral, debt) /// @param _manager Manager contract /// @param _safeId Id of the Safe /// @param _collType CollType of the Safe function getSafeInfo(ISAFEManager _manager, uint _safeId, bytes32 _collType) public view returns (uint, uint) { address vat = _manager.safeEngine(); address urn = _manager.safes(_safeId); (uint collateral, uint debt) = ISAFEEngine(vat).safes(_collType, urn); (,uint rate,,,,) = ISAFEEngine(vat).collateralTypes(_collType); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the Safe /// @param _manager Manager contract /// @param _safeId Id of the Safe function getOwner(ISAFEManager _manager, uint _safeId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.ownsSAFE(_safeId))); return proxy.owner(); } /// @notice Based on the manager type returns the address /// @param _managerType Type of vault manager to use function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.RAI) { return 0xEfe0B4cA532769a3AE758fD82E1426a03A94F185; } } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/ZrxAllowlist.sol"; import "./DFSExchangeData.sol"; import "./DFSExchangeHelper.sol"; import "../exchange/SaverExchangeRegistry.sol"; import "../interfaces/OffchainWrapperInterface.sol"; contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData { string public constant ERR_SLIPPAGE_HIT = "Slippage hit"; string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing"; string public constant ERR_WRAPPER_INVALID = "Wrapper invalid"; string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid"; /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.SELL); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.BUY); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data function takeOrder( ExchangeData memory _exData, ActionType _type ) private returns (bool success, uint256) { if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { return (false, 0); } if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) { return (false, 0); } // send src amount ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount); return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID); ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData); } else { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData); } } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } pragma solidity ^0.6.0; import "./DSAuth.sol"; import "./DSNote.sol"; abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } pragma solidity ^0.6.0; abstract contract IBasicTokenAdapters { bytes32 public collateralType; function decimals() virtual public view returns (uint); function collateral() virtual public view returns (address); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } pragma solidity ^0.6.0; abstract contract ISAFEManager { function lastSAFEID(address) virtual public returns (uint); function safeCan(address, uint, address) virtual public view returns (uint); function collateralTypes(uint) virtual public view returns (bytes32); function ownsSAFE(uint) virtual public view returns (address); function safes(uint) virtual public view returns (address); function safeEngine() virtual public view returns (address); function openSAFE(bytes32, address) virtual public returns (uint); function transferSAFEOwnership(uint, address) virtual public; function allowSAFE(uint, address, uint) virtual public; function handlerAllowed(address, uint) virtual public; function modifySAFECollateralization(uint, int, int) virtual public; function transferCollateral(uint, address, uint) virtual public; function transferInternalCoins(uint, address, uint) virtual public; function quitSystem(uint, address) virtual public; function enterSystem(address, uint) virtual public; function moveSAFE(uint, uint) virtual public; } pragma solidity ^0.6.0; abstract contract ISAFEEngine { struct SAFE { uint256 lockedCollateral; uint256 generatedDebt; } struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } mapping (bytes32 => mapping (address => SAFE )) public safes; mapping (bytes32 => CollateralType) public collateralTypes; mapping (bytes32 => mapping (address => uint)) public tokenCollateral; function safeRights(address, address) virtual public view returns (uint); function coinBalance(address) virtual public view returns (uint); function modifySAFECollateralization(bytes32, address, address, address, int, int) virtual public; function approveSAFEModification(address) virtual public; function transferInternalCoins(address, address, uint) virtual public; function transferSAFECollateralAndDebt(bytes32, address, address, int, int) virtual public; } pragma solidity ^0.6.0; contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } pragma solidity ^0.6.0; abstract contract TokenInterface { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } pragma solidity ^0.6.0; interface ExchangeInterfaceV3 { function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; contract DFSExchangeHelper { string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _user Address of the user /// @param _token Address of the token /// @param _dfsFeeDivider Dfs fee divider /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) { if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { _dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } if (_dfsFeeDivider == 0) { feeAmount = 0; } else { feeAmount = _amount / _dfsFeeDivider; // fee can't go over 10% of the whole amount if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; } address walletAddr = _feeRecipient.getFeeAddr(); if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert(ERR_OFFCHAIN_DATA_INVALID); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _src; } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchangeV3/DFSExchangeData.sol"; abstract contract OffchainWrapperInterface is DFSExchangeData { function takeOrder( ExchangeData memory _exData, ActionType _type ) virtual public payable returns (bool success, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract IFeeRecipient { function getFeeAddr() public view virtual returns (address); function changeWalletAddr(address _newWallet) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "../utils/FlashLoanReceiverBase.sol"; import "../interfaces/DSProxyInterface.sol"; import "../exchangeV3/DFSExchangeCore.sol"; import "./ShifterRegistry.sol"; import "./LoanShifterTaker.sol"; /// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth { address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant SERVICE_FEE = 400; // 0.25% Fee ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendTokenToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(paramData.proxy).owner(); if (paramData.swapType == 1) { // COLL_SWAP (, uint256 amount) = _sell(exchangeData); sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendTokenToProxy( payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)) ); } else { // NO_SWAP just send tokens to proxy sendTokenAndEthToProxy( payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr) ); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall( uint256 _amount, uint256 _fee, bytes memory _params ) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { LoanShifterTaker.LoanShiftData memory shiftData; address proxy; (shiftData, exchangeData, proxy) = abi.decode( _params, (LoanShifterTaker.LoanShiftData, ExchangeData, address) ); bytes memory proxyData1; bytes memory proxyData2; uint256 openDebtAmount = (_amount + _fee); if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER FROM proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount ); } else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND FROM if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature( "changeDebt(address,address,uint256,uint256)", shiftData.debtAddr1, shiftData.debtAddr2, _amount, exchangeData.srcAmount ); } else { proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", shiftData.addrLoan1, shiftData.debtAddr1, shiftData.collAmount, shiftData.debtAmount ); } } if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER TO proxyData2 = abi.encodeWithSignature( "open(uint256,address,uint256)", shiftData.id2, shiftData.addrLoan2, openDebtAmount ); } else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND TO if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2); } else { proxyData2 = abi.encodeWithSignature( "open(address,address,uint256)", shiftData.addrLoan2, shiftData.debtAddr2, openDebtAmount ); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: shiftData.debtAddr1, protocol1: uint8(shiftData.fromProtocol), protocol2: uint8(shiftData.toProtocol), swapType: uint8(shiftData.swapType) }); } function sendTokenAndEthToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function sendTokenToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } else { _proxy.transfer(address(this).balance); } } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {} } pragma solidity ^0.6.0; import "./SafeERC20.sol"; interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../DS/DSProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../shifter/ShifterRegistry.sol"; import "./CompoundCreateTaker.sol"; /// @title Contract that receives the FL from Aave for Creating loans contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner(); _sell(exchangeData); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { CompoundCreateTaker.CreateInfo memory createData; address proxy; (createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee)); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: createData.cCollAddress, cDebtAddr: createData.cBorrowAddress }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; /// @title Opens compound positions with a leverage contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, DFSExchangeData.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../saver/RAISaverProxy.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "../../utils/DydxFlashLoanBase.sol"; contract RAISaverTaker is RAISaverProxy, DydxFlashLoanBase, GasBurner { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; struct SaverData { uint256 flAmount; bool isRepay; uint256 safeId; uint256 gasCost; address joinAddr; ManagerType managerType; } function boostWithLoan( ExchangeData memory _exchangeData, uint256 _safeId, uint256 _gasCost, address _joinAddr, ManagerType _managerType, address _raiSaverFlashLoan ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxDebt = getMaxDebt(managerAddr, _safeId, ISAFEManager(managerAddr).collateralTypes(_safeId)); if (maxDebt >= _exchangeData.srcAmount) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _safeId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = getAvailableEthLiquidity(); SaverData memory saverData = SaverData({ flAmount: loanAmount, isRepay: false, safeId: _safeId, gasCost: _gasCost, joinAddr: _joinAddr, managerType: _managerType }); _flashLoan(_raiSaverFlashLoan, _exchangeData, saverData); } function repayWithLoan( ExchangeData memory _exchangeData, uint256 _safeId, uint256 _gasCost, address _joinAddr, ManagerType _managerType, address _raiSaverFlashLoan ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxColl = getMaxCollateral( managerAddr, _safeId, ISAFEManager(managerAddr).collateralTypes(_safeId), _joinAddr ); if (maxColl >= _exchangeData.srcAmount) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _safeId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = _exchangeData.srcAmount; SaverData memory saverData = SaverData({ flAmount: loanAmount, isRepay: true, safeId: _safeId, gasCost: _gasCost, joinAddr: _joinAddr, managerType: _managerType }); _flashLoan(_raiSaverFlashLoan, _exchangeData, saverData); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _safeId Id of the CDP /// @param _collType Coll type of the CDP function getMaxDebt( address _managerAddr, uint256 _safeId, bytes32 _collType ) public override view returns (uint256) { (uint256 collateral, uint256 debt) = getSafeInfo(ISAFEManager(_managerAddr), _safeId, _collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); return sub(rmul(collateral, safetyPrice), debt); } /// @notice Fetches Eth Dydx liqudity function getAvailableEthLiquidity() internal view returns (uint256 liquidity) { liquidity = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(address RAI_SAVER_FLASH_LOAN, ExchangeData memory _exchangeData, SaverData memory _saverData) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); address managerAddr = getManagerAddr(_saverData.managerType); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_saverData.flAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _saverData.flAmount, RAI_SAVER_FLASH_LOAN); payable(RAI_SAVER_FLASH_LOAN).transfer(msg.value); // 0x fee bytes memory exchangeData = packExchangeData(_exchangeData); operations[1] = _getCallAction(abi.encode(exchangeData, _saverData), RAI_SAVER_FLASH_LOAN); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); ISAFEManager(managerAddr).allowSAFE(_saverData.safeId, RAI_SAVER_FLASH_LOAN, 1); solo.operate(accountInfos, operations); ISAFEManager(managerAddr).allowSAFE(_saverData.safeId, RAI_SAVER_FLASH_LOAN, 0); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../utils/SafeMath.sol"; import "../savings/dydx/ISoloMargin.sol"; contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (public virtually) Sell, // sell an amount of some token (public virtually) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public virtual; function getIsGlobalOperator(address operator) public virtual view returns (bool); function getMarketTokenAddress(uint256 marketId) public virtual view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) public virtual; function getAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) public virtual view returns (address); function getMarketInterestSetter(uint256 marketId) public virtual view returns (address); function getMarketSpreadPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getNumMarkets() public virtual view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) public virtual returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) public virtual; function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual; function getIsLocalOperator(address owner, address operator) public virtual view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public virtual; function getMarginRatio() public virtual view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) public virtual view returns (bool); function getRiskParams() public virtual view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) public virtual view returns (address[] memory, Types.Par[] memory, Types.Wei[] memory); function renounceOwnership() public virtual; function getMinBorrowedValue() public virtual view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) public virtual; function getMarketPrice(uint256 marketId) public virtual view returns (address); function owner() public virtual view returns (address); function isOwner() public virtual view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) public virtual returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public virtual; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getMarketWithInfo(uint256 marketId) public virtual view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual; function getLiquidationSpread() public virtual view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) public virtual view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public virtual view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) public virtual view returns (uint8); function getEarningsRate() public virtual view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual; function getRiskLimits() public virtual view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) public virtual view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual; function ownerSetGlobalOperator(address operator, bool approved) public virtual; function transferOwnership(address newOwner) public virtual; function getAdjustedAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) public virtual view returns (Interest.Rate memory); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/ProxyPermission.sol"; import "../utils/DydxFlashLoanBase.sol"; import "../loggers/DefisaverLogger.sol"; import "../interfaces/ERC20.sol"; /// @title Takes flash loan contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ProtocolInterface.sol"; import "../interfaces/ERC20.sol"; import "../interfaces/ITokenInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "./dydx/ISoloMargin.sol"; import "./SavingsLogger.sol"; import "./dsr/DSRSavingsProtocol.sol"; import "./compound/CompoundSavingsProtocol.sol"; contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } pragma solidity ^0.6.0; abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); function borrowCaps(address) external virtual returns (uint256); } pragma solidity ^0.6.0; contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../DS/DSMath.sol"; abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../compound/helpers/Exponential.sol"; import "../../interfaces/ERC20.sol"; contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; import "./Gem.sol"; abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } pragma solidity ^0.6.0; abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } pragma solidity ^0.6.0; import "./CarefulMath.sol"; contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } } pragma solidity ^0.6.0; contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../compound/helpers/Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for cream contracts contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } pragma solidity ^0.6.0; abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } pragma solidity ^0.6.0; abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CreamSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "../utils/ZrxAllowlist.sol"; import "./SaverExchangeHelper.sol"; import "./SaverExchangeRegistry.sol"; contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return address(this).balance; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../loggers/DefisaverLogger.sol"; import "../../utils/Discount.sol"; import "../../interfaces/Spotter.sol"; import "../../interfaces/Jug.sol"; import "../../interfaces/DaiJoin.sol"; import "../../interfaces/Join.sol"; import "./MCDSaverProxyHelper.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Implements Boost and Repay for MCD CDPs contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } } pragma solidity ^0.6.0; import "./PipInterface.sol"; abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } pragma solidity ^0.6.0; abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } pragma solidity ^0.6.0; import "./Vat.sol"; import "./Gem.sol"; abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../interfaces/Vat.sol"; /// @title Helper methods for MCDSaverProxy contract MCDSaverProxyHelper is DSMath { enum ManagerType { MCD, BPROTOCOL } /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } /// @notice Based on the manager type returns the address /// @param _managerType Type of vault manager to use function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.MCD) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } else if (_managerType == ManagerType.BPROTOCOL) { return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed; } } } pragma solidity ^0.6.0; abstract contract PipInterface { function read() public virtual returns (bytes32); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILoanShifter.sol"; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../mcd/create/MCDCreateProxyActions.sol"; contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(address(manager), _cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(address(manager), _cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(address(manager), _cdpId, _joinAddr, collAmount); // draw debt drawDai(address(manager), _cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } } pragma solidity ^0.6.0; abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "./MCDCreateProxyActions.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../DS/DSProxy.sol"; import "./MCDCreateTaker.sol"; contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData)); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxy(payable(proxy)).owner(); openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, (_collAmount + collSwaped)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; contract MCDCreateTaker is GasBurner { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable burnGas(20) { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } bytes memory packedData = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_createData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../saver/MCDSaverProxy.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0xcBb5DbBCcFbf6aF8AF75d0cbD5646C73d847cd15; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/ITokenInterface.sol"; import "../../DS/DSAuth.sol"; contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "./ISoloMargin.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./RAISaverTaker.sol"; import "../saver/RAISaverProxy.sol"; import "../../savings/dydx/ISoloMargin.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; contract RAISaverFlashLoan is RAISaverProxy, AdminAuth { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function callFunction( address, Account.Info memory, bytes memory _params ) public { ( bytes memory exDataBytes , RAISaverTaker.SaverData memory saverData ) = abi.decode(_params, (bytes, RAISaverTaker.SaverData)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); address managerAddr = getManagerAddr(saverData.managerType); address userProxy = ISAFEManager(managerAddr).ownsSAFE(saverData.safeId); if (saverData.isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } // payback FL, assumes we have weth TokenInterface(WETH_ADDR).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDR).safeTransfer(userProxy, (saverData.flAmount + 2)); } function boostWithLoan( ExchangeData memory _exchangeData, RAISaverTaker.SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(ISAFEManager(managerAddr), _saverData.safeId); bytes32 collType = ISAFEManager(managerAddr).collateralTypes(_saverData.safeId); addCollateral(managerAddr, _saverData.safeId, _saverData.joinAddr, _saverData.flAmount, false); // Draw users Rai uint raiDrawn = drawRai(managerAddr, _saverData.safeId, collType, _exchangeData.srcAmount); // Swap _exchangeData.srcAmount = raiDrawn - takeFee(_saverData.gasCost, raiDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(managerAddr, _saverData.safeId, _saverData.joinAddr, swapedAmount, true); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _saverData.safeId, _saverData.joinAddr, _saverData.flAmount, false); logger.Log(address(this), msg.sender, "RAIFlashBoost", abi.encode(_saverData.safeId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, RAISaverTaker.SaverData memory _saverData ) internal { TokenInterface(WETH_ADDR).withdraw(_saverData.flAmount); address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(ISAFEManager(managerAddr), _saverData.safeId); bytes32 collType = ISAFEManager(managerAddr).collateralTypes(_saverData.safeId); // Swap _exchangeData.srcAmount = _saverData.flAmount; _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(managerAddr, _saverData.safeId, collType, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.safeId, collType, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _saverData.safeId, _saverData.joinAddr, _saverData.flAmount, false); logger.Log(address(this), msg.sender, "RAIFlashRepay", abi.encode(_saverData.safeId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(address _managerAddr, uint _safeId, bytes32 _collType, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(safeEngine), ISAFEManager(_managerAddr).safes(_safeId), ISAFEManager(_managerAddr).safes(_safeId), _collType); if (_paybackAmount > debt) { ERC20(RAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust,) = safeEngine.collateralTypes(_collType); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(RAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, address market, uint256 rateMode, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } else { functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelperV2 is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; uint public constant STABLE_ID = 1; uint public constant VARIABLE_ID = 2; /// @notice Calculates the gas cost for transaction /// @param _oracleAddress address of oracle used /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); gasCost = _gasCost; // gas cost can't go over 10% of the whole amount if (gasCost > (_amount / 10)) { gasCost = _amount / 10; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) internal { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) internal { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) { return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProviderV2 { event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } interface ILendingPoolV2 { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } pragma solidity ^0.6.0; /************ @title IPriceOracleGetterAave interface @notice Interface for the Aave price oracle.*/ abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; abstract contract IAaveProtocolDataProviderV2 { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external virtual view returns (TokenData[] memory); function getAllATokens() external virtual view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external virtual view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external virtual view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external virtual view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external virtual view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../AaveHelperV2.sol"; import "../../../utils/GasBurner.sol"; import "../../../auth/AdminAuth.sol"; import "../../../auth/ProxyPermission.sol"; import "../../../utils/DydxFlashLoanBase.sol"; import "../../../loggers/DefisaverLogger.sol"; import "../../../interfaces/ProxyRegistryInterface.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../interfaces/ERC20.sol"; import "../../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 { address payable public constant AAVE_RECEIVER = 0xf852572bCdD36648999722751c29F40fE584da43; // leaving _flAmount to be the same as the older version function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; // for repay we are using regular flash loan with paying back the flash loan + premium uint256[] memory modes = new uint256[](1); modes[0] = 0; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } // leaving _flAmount to be the same as the older version function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; uint256[] memory modes = new uint256[](1); modes[0] = _rateMode; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; import "./DSProxyInterface.sol"; abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Flipper.sol"; import "../../interfaces/Gem.sol"; contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); if(Join(_joinAddr).dec() != 18) { amount = amount / (10**(18 - Join(_joinAddr).dec())); } Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } pragma solidity ^0.6.0; abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./saver/MCDSaverProxyHelper.sol"; import "../interfaces/Spotter.sol"; contract MCDLoanInfo is MCDSaverProxyHelper { Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); struct VaultInfo { address owner; uint256 ratio; uint256 collateral; uint256 debt; bytes32 ilk; address urn; } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) { address urn = manager.urns(_cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint256 collateral, uint256 debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); vaultInfo = VaultInfo({ owner: manager.owns(_cdpId), ratio: getRatio(_cdpId, ilk), collateral: collateral, debt: debt, ilk: ilk, urn: urn }); } function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) { vaultInfos = new VaultInfo[](_cdps.length); for (uint256 i = 0; i < _cdps.length; i++) { vaultInfos[i] = getVaultInfo(_cdps[i]); } } function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) { ratios = new uint256[](_cdps.length); for (uint256 i = 0; i<_cdps.length; i++) { bytes32 ilk = manager.ilks(_cdps[i]); ratios[i] = getRatio(_cdps[i], ilk); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "./StaticV2.sol"; import "../saver/MCDSaverProxy.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../auth/AdminAuth.sol"; /// @title Handles subscriptions for automatic monitoring contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } pragma solidity ^0.6.0; /// @title Implements enum Method abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./ISubscriptionsV2.sol"; import "./StaticV2.sol"; import "./MCDMonitorProxyV2.sol"; /// @title Implements logic that allows bots to call Boost and Repay contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 800000000000; // 800 gwei uint public REPAY_GAS_COST = 1000000; uint public BOOST_GAS_COST = 1000000; bytes4 public REPAY_SELECTOR = 0xf360ce20; bytes4 public BOOST_SELECTOR = 0x8ec2ae25; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 1000000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./StaticV2.sol"; abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Implements logic for calling MCDSaverProxy always from same contract contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; uint public MIN_CHANGE_PERIOD = 6 * 1 hours; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "./Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for Compound contracts contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; import "../../compound/helpers/CompoundSaverHelper.sol"; contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CompoundSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CompoundSaverFlashProxy is DFSExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee _exData.srcAmount = (borrowAmount + _flashLoanData[0]); _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Imports cream position from the account to DSProxy contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } pragma solidity ^0.6.0; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Receiver of Dydx flash loan and performs the fl repay/boost logic /// @notice Must have a dust amount of WETH on the contract for 2 wei dydx fee contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; ManagerType managerType; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay, uint8 managerType ) = abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr, managerType: ManagerType(managerType) }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId)); uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../mcd/saver/MCDSaverProxyHelper.sol"; import "./MCDCloseTaker.sol"; contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData)); CloseData memory closeData = CloseData({ cdpId: closeDataSent.cdpId, collAmount: closeDataSent.collAmount, daiAmount: closeDataSent.daiAmount, minAccepted: closeDataSent.minAccepted, joinAddr: closeDataSent.joinAddr, proxy: proxy, flFee: _fee, toDai: closeDataSent.toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = user; address managerAddr = getManagerAddr(closeDataSent.managerType); closeCDP(closeData, exchangeData, user, managerAddr); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user, address _managerAddr ) internal { paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_managerAddr, _closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); } else { _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee); (, daiSwaped) = _buy(_exchangeData); } address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0); Manager(_managerAddr).flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = Manager(_managerAddr).urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == EXCHANGE_WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; ManagerType managerType; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable burnGas(20) { mcdCloseFlashLoan.transfer(msg.value); // 0x fee address managerAddr = getManagerAddr(_closeData.managerType); if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId)); } Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); bytes memory packedData = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_closeData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchange/SaverExchangeCore.sol"; contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "../interfaces/IFeeRecipient.sol"; import "./SaverExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { address walletAddr = _feeRecipient.getFeeAddr(); feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapExchangeInterface.sol"; import "../../interfaces/UniswapFactoryInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } pragma solidity ^0.6.0; abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "./SaverExchangeHelper.sol"; contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/SafeERC20.sol"; contract DFSPrices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers, bytes[] memory _additionalData ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type, bytes memory _additionalData ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); /// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell /// @dev safeApprove is modified to always first set approval to 0, then to exact amount if (_type == ActionType.SELL) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from Scp and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up writeUint256(_exData.offchainData.callData, 36, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelper is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/reflexer/IGetSafes.sol"; import "../interfaces/reflexer/ISAFEEngine.sol"; import "../interfaces/reflexer/ISAFEManager.sol"; import "../interfaces/reflexer/IOracleRelayer.sol"; import "../interfaces/reflexer/IMedianOracle.sol"; import "../interfaces/reflexer/ITaxCollector.sol"; contract RaiLoanInfo is DSMath { // mainnet address public constant GET_SAFES_ADDR = 0xdf4BC9aA98cC8eCd90Ba2BEe73aD4a1a9C8d202B; address public constant MANAGER_ADDR = 0xEfe0B4cA532769a3AE758fD82E1426a03A94F185; address public constant SAFE_ENGINE_ADDRESS = 0xCC88a9d330da1133Df3A7bD823B95e52511A6962; address public constant ORACLE_RELAYER_ADDRESS = 0x4ed9C0dCa0479bC64d8f4EB3007126D5791f7851; address public constant MEDIAN_ORACLE_ADDRESS = 0x12A5E1c81B10B264A575930aEae80681DDF595fe; address public constant TAX_COLLECTOR_ADDRESS = 0xcDB05aEda142a1B0D6044C09C64e4226c1a281EB; // kovan // address public constant GET_SAFES_ADDR = 0x702dcf4a8C3bBBd243477D5704fc45F2762D3826; // address public constant MANAGER_ADDR = 0x807C8eCb73d9c8203d2b1369E678098B9370F2EA; // address public constant SAFE_ENGINE_ADDRESS = 0x7f63fE955fFF8EA474d990f1Fc8979f2C650edbE; // address public constant ORACLE_RELAYER_ADDRESS = 0xE5Ae4E49bEA485B5E5172EE6b1F99243cB15225c; // address public constant MEDIAN_ORACLE_ADDRESS = 0x82bEAd00751EFA3286c9Dd17e4Ea2570916B3944; // address public constant TAX_COLLECTOR_ADDRESS = 0xc1a94C5ad9FCD79b03F79B34d8C0B0C8192fdc16; struct SafeInfo { uint256 safeId; uint256 coll; uint256 debt; address safeAddr; bytes32 collType; } struct CollInfo { uint256 debtCeiling; uint256 currDebtAmount; uint256 currRate; uint256 dust; uint256 safetyPrice; uint256 liqPrice; uint256 assetPrice; uint256 liqRatio; uint256 stabilityFee; } struct RaiInfo { uint256 redemptionPrice; uint256 currRaiPrice; uint256 redemptionRate; } function getCollateralTypeInfo(bytes32 _collType) public returns (CollInfo memory collInfo) { ( uint256 debtAmount, uint256 accumulatedRates, uint256 safetyPrice, uint256 debtCeiling, uint256 debtFloor, uint256 liquidationPrice ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); (, uint liqRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (uint stabilityFee,) = ITaxCollector(TAX_COLLECTOR_ADDRESS).collateralTypes(_collType); collInfo = CollInfo({ debtCeiling: debtCeiling, currDebtAmount: debtAmount, currRate: accumulatedRates, dust: debtFloor, safetyPrice: safetyPrice, liqPrice: liquidationPrice, assetPrice: getPrice(_collType), liqRatio: liqRatio, stabilityFee: stabilityFee }); } function getCollAndRaiInfo(bytes32 _collType) public returns (CollInfo memory collInfo, RaiInfo memory raiInfo) { collInfo = getCollateralTypeInfo(_collType); raiInfo = getRaiInfo(); } function getPrice(bytes32 _collType) public returns (uint256) { (, uint256 safetyCRatio) = IOracleRelayer(ORACLE_RELAYER_ADDRESS).collateralTypes(_collType); (, , uint256 safetyPrice, , , ) = ISAFEEngine(SAFE_ENGINE_ADDRESS).collateralTypes(_collType); uint256 redemptionPrice = IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(); return rmul(rmul(safetyPrice, redemptionPrice), safetyCRatio); } function getRaiInfo() public returns (RaiInfo memory raiInfo) { raiInfo = RaiInfo({ redemptionPrice: IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionPrice(), currRaiPrice: IMedianOracle(MEDIAN_ORACLE_ADDRESS).read(), redemptionRate: IOracleRelayer(ORACLE_RELAYER_ADDRESS).redemptionRate() }); } function getSafeInfo(uint256 _safeId) public view returns (SafeInfo memory safeInfo) { address safeAddr = ISAFEManager(MANAGER_ADDR).safes(_safeId); bytes32 collType = ISAFEManager(MANAGER_ADDR).collateralTypes(_safeId); (uint256 coll, uint256 debt) = ISAFEEngine(SAFE_ENGINE_ADDRESS).safes(collType, safeAddr); safeInfo = SafeInfo({ safeId: _safeId, coll: coll, debt: debt, safeAddr: safeAddr, collType: collType }); } function getUserSafes(address _user) public view returns ( uint256[] memory ids, address[] memory safes, bytes32[] memory collateralTypes ) { return IGetSafes(GET_SAFES_ADDR).getSafesAsc(MANAGER_ADDR, _user); } function getUserSafesFullInfo(address _user) public view returns (SafeInfo[] memory safeInfos) { (uint256[] memory ids, , ) = getUserSafes(_user); safeInfos = new SafeInfo[](ids.length); for (uint256 i = 0; i < ids.length; ++i) { safeInfos[i] = getSafeInfo(ids[i]); } } function getFullInfo(address _user, bytes32 _collType) public returns ( CollInfo memory collInfo, RaiInfo memory raiInfo, SafeInfo[] memory safeInfos ) { collInfo = getCollateralTypeInfo(_collType); raiInfo = getRaiInfo(); safeInfos = getUserSafesFullInfo(_user); } } pragma solidity ^0.6.0; abstract contract IGetSafes { function getSafesAsc(address manager, address guy) external virtual view returns (uint[] memory ids, address[] memory safes, bytes32[] memory collateralTypes); function getSafesDesc(address manager, address guy) external virtual view returns (uint[] memory ids, address[] memory safes, bytes32[] memory collateralTypes); } pragma solidity ^0.6.0; abstract contract IMedianOracle { function read() external virtual view returns (uint256); } pragma solidity ^0.6.0; import "./DSProxy.sol"; abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../utils/SafeERC20.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../DS/DSProxy.sol"; import "../../AaveHelperV2.sol"; import "../../../auth/AdminAuth.sol"; import "../../../exchangeV3/DFSExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal { (, uint swappedAmount) = _sell(_exchangeData); address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens uint256 msgValue = 0; address token = _exchangeData.destAddr; // sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { msgValue = swappedAmount; token = ETH_ADDR; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // deposit collateral on behalf of user DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "deposit(address,address,uint256)", _market, token, swappedAmount ) ); } function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal { // we will withdraw exactly the srcAmount, as fee we keep before selling uint valueToWithdraw = _exchangeData.srcAmount; // take out the fee wee need to pay and sell the rest _exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee; (, uint swappedAmount) = _sell(_exchangeData); // set protocol fee left to eth balance of this address // but if destAddr is eth or weth, this also includes that value so we need to substract it uint protocolFeeLeft = address(this).balance; address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens uint256 msgValue = 0; if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { protocolFeeLeft -= swappedAmount; msgValue = swappedAmount; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // first payback the loan with swapped amount DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "payback(address,address,uint256,uint256)", _market, _exchangeData.destAddr, swappedAmount, _rateMode ) ); // if some tokens left after payback (full repay) we need to return it back to the proxy owner require(user != address(0)); // be sure that we fetched the user correctly if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { // keep protocol fee for tx.origin, but the rest of the balance return to the user payable(user).transfer(address(this).balance - protocolFeeLeft); } else { // in case its a token, just return whole value back to the user, as protocol fee is always in eth uint amount = ERC20(_exchangeData.destAddr).balanceOf(address(this)); ERC20(_exchangeData.destAddr).safeTransfer(user, amount); } // pull the amount we flash loaned in collateral to be able to payback the debt DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw)); } function executeOperation( address[] calldata, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) public returns (bool) { ( bytes memory exchangeDataBytes, address market, uint256 gasCost, uint256 rateMode, bool isRepay, address proxy ) = abi.decode(params, (bytes,address,uint256,uint256,bool,address)); address lendingPool = ILendingPoolAddressesProviderV2(market).getLendingPool(); require(msg.sender == lendingPool, "Callbacks only allowed from Aave"); require(initiator == proxy, "initiator isn't proxy"); ExchangeData memory exData = unpackExchangeData(exchangeDataBytes); exData.user = DSAuth(proxy).owner(); exData.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // this is to avoid stack too deep uint fee = premiums[0]; uint totalValueToReturn = exData.srcAmount + fee; // if its repay, we are using regular flash loan and payback the premiums if (isRepay) { repay(exData, market, gasCost, proxy, rateMode, fee); address token = exData.srcAddr; if (token == ETH_ADDR || token == WETH_ADDRESS) { // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)(); token = WETH_ADDRESS; } ERC20(token).safeApprove(lendingPool, totalValueToReturn); } else { boost(exData, market, gasCost, proxy); } tx.origin.transfer(address(this).balance); return true; } /// @dev allow contract to receive eth from sell receive() external override payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImportV2 is AaveHelperV2, AdminAuth { using SafeERC20 for ERC20; address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address market, address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market); uint256 globalBorrowAmountStable = 0; uint256 globalBorrowAmountVariable = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user); if (borrowsStable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID)); globalBorrowAmountStable = borrowsStable; } if (borrowsVariable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID)); globalBorrowAmountVariable = borrowsVariable; } } if (globalBorrowAmountVariable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID); } if (globalBorrowAmountStable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID); } (address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken); // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal { // payback on behalf of user if (_token != ETH_ADDR) { ERC20(_token).safeApprove(_proxy, _amount); DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } else { DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); uint256 globalBorrowAmount = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, ERC20(aCollateralToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelper.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxy is GasBurner, DFSExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); // uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral // _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } else { destAmount = _data.srcAmount; destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelperV2.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/TokenInterface.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this)); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // swap (, destAmount) = _sell(_data); } // take gas cost at the end destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); // if destAmount higher than borrow repay whole debt uint borrow; if (_rateMode == STABLE_ID) { (,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } else { (,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this))); // first return 0x fee to tx.origin as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); // borrow amount ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this)); // take gas cost at the beginning _data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } (, destAmount) = _sell(_data); } else { destAmount = _data.srcAmount; } if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "./AaveHelperV2.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 { using SafeERC20 for ERC20; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); if (_tokenAddr == ETH_ADDR) { require(msg.value == _amount); TokenInterface(WETH_ADDRESS).deposit{value: _amount}(); _tokenAddr = WETH_ADDRESS; } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be withdrawn /// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { // if weth, pull to proxy and return ETH to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this)); // needs to use balance of in case that amount is -1 for whole debt TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); msg.sender.transfer(address(this).balance); } else { // if not eth send directly to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender); } } /// @notice User borrows tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this)); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender)); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this))); if (_tokenAddr == WETH_ADDRESS) { // Pull if we have any eth leftover TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this))); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this))); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } // stable = 1, variable = 2 function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode); } function changeToWeth(address _token) private view returns(address) { if (_token == ETH_ADDR) { return WETH_ADDRESS; } return _token; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; import "./AaveHelperV2.sol"; import "../interfaces/ILendingPoolV2.sol"; contract AaveSafetyRatioV2 is AaveHelperV2 { function getSafetyRatio(address _market, address _user) public view returns(uint256) { ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool()); (,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user); if (totalDebtETH == 0) return uint256(0); return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./AaveMonitorProxyV2.sol"; import "./AaveSubscriptionsV2.sol"; import "../AaveSafetyRatioV2.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorV2"; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; AaveMonitorProxyV2 public aaveMonitorProxy; AaveSubscriptionsV2 public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxyV2(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptionsV2(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepayV2", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoostV2", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptionsV2.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptionsV2.AaveHolder memory holder; holder = subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxyV2 is AdminAuth { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorProxyV2"; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Owner is able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Owner is able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point owner is able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptionsV2 is AdminAuth { string public constant NAME = "AaveSubscriptionsV2"; struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatioV2.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; contract AaveLoanInfoV2 is AaveSafetyRatioV2 { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowStableAmounts; uint256[] borrowVariableAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRateVariable; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; bool borrowinEnabled; bool stableBorrowRateEnabled; } struct ReserveData { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; } struct UserToken { address token; uint256 balance; uint256 borrowsStable; uint256 borrowsVariable; uint256 stableBorrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user function getRatio(address _market, address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_market, _user); } /// @notice Fetches Aave prices for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens); } /// @notice Fetches Aave collateral factors for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } } function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address _market, address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_market, _users[i]); } } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]); (address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: aToken, underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) { ( , // uint256 decimals uint256 ltv, uint256 liquidationThreshold, , // uint256 liquidationBonus , // uint256 reserveFactor bool usageAsCollateralEnabled, bool borrowinEnabled, bool stableBorrowRateEnabled, , // bool isActive // bool isFrozen ) = _dataProvider.getReserveConfigurationData(_token); ReserveData memory t; ( t.availableLiquidity, t.totalStableDebt, t.totalVariableDebt, t.liquidityRate, t.variableBorrowRate, t.stableBorrowRate, , , , ) = _dataProvider.getReserveData(_token); (address aToken,,) = _dataProvider.getReserveTokensAddresses(_token); uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token); _tokenInfo = TokenInfoFull({ aTokenAddress: aToken, underlyingTokenAddress: _token, supplyRate: t.liquidityRate, borrowRateVariable: t.variableBorrowRate, borrowRateStable: t.stableBorrowRate, totalSupply: ERC20(aToken).totalSupply(), availableLiquidity: t.availableLiquidity, totalBorrow: t.totalVariableDebt+t.totalStableDebt, collateralFactor: ltv, liquidationRatio: liquidationThreshold, price: price, usageAsCollateralEnabled: usageAsCollateralEnabled, borrowinEnabled: borrowinEnabled, stableBorrowRateEnabled: stableBorrowRateEnabled }); } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _market, address _user) public view returns (LoanData memory data) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowStableAmounts: new uint[](reserves.length), borrowVariableAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i].tokenAddress; (uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowsStable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowStableAmounts[borrowPos] = userBorrowBalanceEth; } // Sum up debt in Eth if (borrowsVariable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowVariableAmounts[borrowPos] = userBorrowBalanceEth; } if (borrowsStable > 0 || borrowsVariable > 0) { borrowPos++; } } data.ratio = uint128(getSafetyRatio(_market, _user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address _market, address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_market, _users[i]); } } } pragma solidity ^0.6.0; import "./AaveHelper.sol"; contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "./AaveMonitorProxy.sol"; import "./AaveSubscriptions.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../AaveSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatio.sol"; contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; uint256 borrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,userTokens[i].borrowRate,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "./DFSExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./DFSExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587); function callSell(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(dfsExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { dfsExchange = DFSExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/BotRegistry.sol"; import "../../utils/GasBurner.sol"; import "./CompoundMonitorProxy.sol"; import "./CompoundSubscriptions.sol"; import "../../interfaces/GasTokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../CompoundSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1500000; uint public BOOST_GAS_COST = 1000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin { compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Compound automatization contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "./helpers/Exponential.sol"; contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompoundSafetyRatio.sol"; import "./helpers/CompoundSaverHelper.sol"; /// @title Gets data about Compound positions contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; uint borrowCap; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]), borrowCap: comp.borrowCaps(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "../compound/helpers/Exponential.sol"; contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CreamSafetyRatio.sol"; import "./helpers/CreamSaverHelper.sol"; /// @title Gets data about cream positions contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic cream interactions through the DSProxy contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic compound interactions through the DSProxy contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompBalance.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../CompoundBasicProxy.sol"; contract CompLeverage is DFSExchangeCore, CompBalance { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.user = msg.sender; exchangeData.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../helpers/Exponential.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface( 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B ); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint256) { uint256 compBalance = 0; for (uint256 i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance = add_(comp.compAccrued(_user), compBalance); compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getClaimableAssets(address[] memory _cTokens, address _user) public view returns (bool[] memory supplyClaims, bool[] memory borrowClaims) { supplyClaims = new bool[](_cTokens.length); borrowClaims = new bool[](_cTokens.length); for (uint256 i = 0; i < _cTokens.length; ++i) { supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0; borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0; } } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint256 supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: comp.compSupplierIndex(_cToken, _supplier) }); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = supplierDelta; } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint256 borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: comp.compBorrowerIndex(_cToken, _borrower) }); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_( CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex ); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = borrowerDelta; } } } pragma solidity ^0.6.0; import "../../interfaces/ERC20.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./SaverExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchange/SaverExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CreamSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CompoundSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; _exData.srcAmount = borrowAmount; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Imports Compound position from the account to DSProxy contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve DSProxy to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this)); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/ICompoundSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = _flAmount; // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _market, _rateMode, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _market Market in which we want to import /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _market, address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_market, _collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxyV2 is ProxyPermission { string public constant NAME = "AaveSubscriptionsProxyV2"; address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD; address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; import "../../DS/DSGuard.sol"; import "../../DS/DSAuth.sol"; contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; import "../../auth/AdminAuth.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { (address cCollAddr, address cBorrowAddr, address proxy) = abi.decode(_params, (address, address, address)); address user = DSProxyInterface(proxy).owner(); uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowAddr, _amount); // repay compound debt on behalf of the user require( CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0, "Repay borrow behalf fail" ); bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance); DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData); // borrow debt now on ds proxy bytes memory borrowProxyCallData = formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData); // repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call to pull tokens to DSProxy /// @param _cTokenAddr CToken address of the collateral /// @param _amount Amount of cTokens to pull function formatDSProxyPullTokensCall( address _cTokenAddr, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "pullTokens(address,uint256)", _cTokenAddr, _amount ); } /// @notice Formats function data call borrow through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed function formatDSProxyBorrowCall( address _cCollToken, address _cBorrowToken, address _borrowToken, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount ); } } pragma solidity ^0.6.0; import "../../interfaces/OsmMom.sol"; import "../../interfaces/Osm.sol"; import "../../auth/AdminAuth.sol"; import "../../interfaces/Manager.sol"; contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } pragma solidity ^0.6.0; abstract contract OsmMom { mapping (bytes32 => address) public osms; } pragma solidity ^0.6.0; abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } pragma solidity ^0.6.0; import "./ERC20.sol"; //TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); }
Based on the manager type returns the address _managerType Type of vault manager to use
function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.RAI) { return 0xEfe0B4cA532769a3AE758fD82E1426a03A94F185; } }
475,467
pragma solidity ^0.4.24; contract owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) revert(); _; } function transferOwnership(address newOwner) onlyOwner private { owner = newOwner; } } // ---------------------------------------------------------------------------------------------- // Original from: // https://theethereum.wiki/w/index.php/ERC20_Token_Standard // (c) BokkyPooBah 2017. The MIT Licence. // ---------------------------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 contract ERC20Interface { // Get the total token supply function totalSupply() constant returns (uint256 totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) constant public returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // Send _value amount of token from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // 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. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) public returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant public returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /// @title Yoyo Ark Coin (YAC) contract YoyoArkCoin is owned, ERC20Interface { // Public variables of the token string public constant standard = 'ERC20'; string public constant name = 'Yoyo Ark Coin'; string public constant symbol = 'YAC'; uint8 public constant decimals = 18; uint public registrationTime = 0; bool public registered = false; uint256 totalTokens = 960 * 1000 * 1000 * 10**18; // This creates an array with all balances mapping (address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // These are related to YAC team members mapping (address => bool) public frozenAccount; mapping (address => uint[3]) public frozenTokens; // Variable of token frozen rules for YAC team members. uint public unlockat; // Constructor constructor() public { } // This unnamed function is called whenever someone tries to send ether to it function () private { revert(); // Prevents accidental sending of ether } function totalSupply() constant public returns (uint256) { return totalTokens; } // What is the balance of a particular account? function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) public returns (bool success) { if (!registered) return false; if (_amount <= 0) return false; if (frozenRules(msg.sender, _amount)) return false; if (balances[msg.sender] >= _amount && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // 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) { if (!registered) return false; if (_amount <= 0) return false; if (frozenRules(_from, _amount)) return false; if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Register for Token Initialize, /// 100% of total Token will initialize to dev Account. function initRegister() public { // (85%) of total supply to sender contract balances[msg.sender] = 960 * 1000 * 1000 * 10**18; // Frozen 15% of total supply for team members. registered = true; registrationTime = now; unlockat = registrationTime + 6 * 30 days; // Frozen rest (15%) of total supply for development team and contributors // 144,000,000 * 10**18; frozenForTeam(); } /// @dev Frozen for the team members. function frozenForTeam() internal { uint totalFrozeNumber = 144 * 1000 * 1000 * 10**18; freeze(msg.sender, totalFrozeNumber); } /// @dev Frozen 15% of total supply for team members. /// @param _account The address of account to be frozen. /// @param _totalAmount The amount of tokens to be frozen. function freeze(address _account, uint _totalAmount) public onlyOwner { frozenAccount[_account] = true; frozenTokens[_account][0] = _totalAmount; // 100% of locked token within 6 months } /// @dev Token frozen rules for token holders. /// @param _from The token sender. /// @param _value The token amount. function frozenRules(address _from, uint256 _value) internal returns (bool success) { if (frozenAccount[_from]) { if (now < unlockat) { // 100% locked within the first 6 months. if (balances[_from] - _value < frozenTokens[_from][0]) return true; } else { // 100% unlocked after 6 months. frozenAccount[_from] = false; } } return false; } }
Token frozen rules for token holders. _from The token sender. _value The token amount. 100% locked within the first 6 months. 100% unlocked after 6 months.
function frozenRules(address _from, uint256 _value) internal returns (bool success) { if (frozenAccount[_from]) { if (now < unlockat) { if (balances[_from] - _value < frozenTokens[_from][0]) return true; frozenAccount[_from] = false; } } return false; }
10,235,280
./partial_match/3/0xe219503aa238a7e5226989FBddE44eaDA56F0a66/sources/TramsMaster.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } require(lpTokenPID[address(_lpToken)] == 0, "TramsMaster:duplicate add."); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTramsPerShare: 0 }) ); lpTokenPID[address(_lpToken)] = poolInfo.length; }
5,178,048
./full_match/43114/0x5EE8198876839441082289A1853Bd7644A3CD94B/sources/MutantAxApes.sol
See {IERC721-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public payable virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); }
4,540,917
./partial_match/1/0xD1C833b46266CcF6060e90B69161FCEe9C66E826/sources/src/NightWatchMetadata.sol
Get the token URI for token metadata tokenId Token ID return string Token URI for token metadata
function tokenURI( uint256 tokenId ) external view virtual override returns (string memory) { return string(abi.encodePacked(_baseURI, LibString.toString(tokenId))); }
15,944,947
// SPDX-License-Identifier: UNLICENSED // The SpellBook // This contract stores funds, handles their transfers, supports flash loans and strategies. // Copyright (c) 2021 theeEnchantress - All Rights Reserved // Twitter: @0xBuns pragma solidity ^0.8.7; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable not-rely-on-time // solhint-disable no-inline-assembly interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); // EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File contracts/interfaces/IFlashLoan.sol // License-Identifier: MIT interface IFlashBorrower { function onFlashLoan( address sender, IERC20 token, uint256 amount, uint256 fee, bytes calldata data ) external; } interface IBatchFlashBorrower { function onBatchFlashLoan( address sender, IERC20[] calldata tokens, uint256[] calldata amounts, uint256[] calldata fees, bytes calldata data ) external; } // File contracts/interfaces/IWETH.sol // License-Identifier: MIT interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // File contracts/interfaces/IStrategy.sol // License-Identifier: MIT interface IStrategy { // Send the assets to the Strategy and call skim to invest them function skim(uint256 amount) external; // Harvest any profits made converted to the asset and pass them to the caller function harvest(uint256 balance, address sender) external returns (int256 amountAdded); // Withdraw assets. The returned amount can differ from the requested amount due to rounding. // The actualAmount should be very close to the amount. // The difference should NOT be used to report a loss. That's what harvest is for. function withdraw(uint256 amount) external returns (uint256 actualAmount); // Withdraw all assets in the safest way possible. This shouldn't fail. function exit(uint256 balance) external returns (int256 amountAdded); } library PossessedERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall( abi.encodeWithSelector(SIG_SYMBOL) ); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall( abi.encodeWithSelector(SIG_NAME) ); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall( abi.encodeWithSelector(SIG_DECIMALS) ); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(SIG_TRANSFER, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "PossessedERC20: Transfer failed" ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "PossessedERC20: TransferFrom failed" ); } } // a library for performing overflow-safe math (https://github.com/dapphub/ds-math) library PossessedMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "PossessedMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "PossessedMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "PossessedMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= type(uint128).max, "PossessedMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= type(uint64).max, "PossessedMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= type(uint32).max, "PossessedMath: uint32 Overflow"); c = uint32(a); } } library PossessedMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "PossessedMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "PossessedMath: Underflow"); } } library PossessedMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "PossessedMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "PossessedMath: Underflow"); } } library PossessedMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "PossessedMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "PossessedMath: Underflow"); } } struct Rebase { uint128 elastic; uint128 base; } library RebaseLibrary { using PossessedMath for uint256; using PossessedMath128 for uint128; function toBase( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (uint256 base) { if (total.elastic == 0) { base = elastic; } else { base = elastic.mul(total.base) / total.elastic; if (roundUp && base.mul(total.elastic) / total.base < elastic) { base = base.add(1); } } } function toElastic( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (uint256 elastic) { if (total.base == 0) { elastic = base; } else { elastic = base.mul(total.elastic) / total.base; if (roundUp && elastic.mul(total.base) / total.elastic < base) { elastic = elastic.add(1); } } } function add( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (Rebase memory, uint256 base) { base = toBase(total, elastic, roundUp); total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return (total, base); } function sub( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (Rebase memory, uint256 elastic) { elastic = toElastic(total, base, roundUp); total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return (total, elastic); } function add( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return total; } function sub( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return total; } function addElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.add(elastic.to128()); } function subElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic = total.elastic.sub(elastic.to128()); } } // Source: Ownable.sol + Claimable.sol // Edited by the Enchantress contract PossessedOwnableData { address public owner; address public pendingOwner; } contract PossessedOwnable is PossessedOwnableData { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); address private constant ZERO_ADDRESS = address(0); constructor() { owner = msg.sender; emit OwnershipTransferred(ZERO_ADDRESS, msg.sender); } function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require( newOwner != ZERO_ADDRESS || renounce, "Ownable: zero address" ); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = ZERO_ADDRESS; } else { // Effects pendingOwner = newOwner; } } function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require( msg.sender == _pendingOwner, "Ownable: caller != pending owner" ); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = ZERO_ADDRESS; } modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } interface IMasterContract { function init(bytes calldata data) external payable; } contract PossessedFactory { event LogDeploy( address indexed masterContract, bytes data, address indexed cloneAddress ); mapping(address => address) public masterContractOf; // Mapping from clone contracts to their masterContract // Deploys a given master Contract as a clone. function deploy( address masterContract, bytes calldata data, bool useCreate2 ) public payable { require( masterContract != address(0), "PossessedFactory: No masterContract" ); bytes20 targetBytes = bytes20(masterContract); // Takes the first 20 bytes of the masterContract's address address cloneAddress; // Address where the clone contract will reside. if (useCreate2) { // each masterContract has different code already. So clones are distinguished by their data only. bytes32 salt = keccak256(data); // Creates clone, more info here: https://blog.openzeppelin.com/deep-dive-into-the-minimal-proxy-contract/ assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) cloneAddress := create2(0, clone, 0x37, salt) } } else { assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) cloneAddress := create(0, clone, 0x37) } } masterContractOf[cloneAddress] = masterContract; IMasterContract(cloneAddress).init{value: msg.value}(data); emit LogDeploy(masterContract, data, cloneAddress); } } // File contracts/MasterContractManager.sol // License-Identifier: UNLICENSED contract MasterContractManager is PossessedOwnable, PossessedFactory { event LogWhiteListMasterContract( address indexed masterContract, bool approved ); event LogSetMasterContractApproval( address indexed masterContract, address indexed user, bool approved ); event LogRegisterProtocol(address indexed protocol); // masterContract to user to approval state mapping(address => mapping(address => bool)) public masterContractApproved; // masterContract to whitelisted state for approval without signed message mapping(address => bool) public whitelistedMasterContracts; // user nonces for masterContract approvals mapping(address => uint256) public nonces; bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); // See https://eips.ethereum.org/EIPS/eip-191 string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; bytes32 private constant APPROVAL_SIGNATURE_HASH = keccak256( "SetMasterContractApproval(string warning,address user,address masterContract,bool approved,uint256 nonce)" ); // solhint-disable-next-line var-name-mixedcase bytes32 private immutable DOMAIN_SEPARATOR; constructor() { uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_SEPARATOR_SIGNATURE_HASH, "SpellBook V2", chainId, address(this) ) ); } function registerProtocol() public { masterContractOf[msg.sender] = msg.sender; emit LogRegisterProtocol(msg.sender); } function whitelistMasterContract(address masterContract, bool approved) public onlyOwner { // Checks require(masterContract != address(0), "MasterCMgr: Cannot approve 0"); // Effects whitelistedMasterContracts[masterContract] = approved; emit LogWhiteListMasterContract(masterContract, approved); } // F4 - Check behaviour for all function arguments when wrong or extreme // F4: Don't allow masterContract 0 to be approved. Unknown contracts will have a masterContract of 0. // F4: User can't be 0 for signed approvals because the recoveredAddress will be 0 if ecrecover fails function setMasterContractApproval( address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) public { // Checks require(masterContract != address(0), "MasterCMgr: masterC not set"); // Important for security // If no signature is provided, the fallback is executed if (r == 0 && s == 0 && v == 0) { require(user == msg.sender, "MasterCMgr: user not sender"); require( masterContractOf[user] == address(0), "MasterCMgr: user is clone" ); require( whitelistedMasterContracts[masterContract], "MasterCMgr: not whitelisted" ); } else { // Important for security - any address without masterContract has address(0) as masterContract // So approving address(0) would approve every address, leading to full loss of funds // Also, ecrecover returns address(0) on failure. So we check this: require(user != address(0), "MasterCMgr: User cannot be 0"); // C10 - Protect signatures against replay, use nonce and chainId (SWC-121) // C10: nonce + chainId are used to prevent replays // C11 - All signatures strictly EIP-712 (SWC-117 SWC-122) // C11: signature is EIP-712 compliant // C12 - abi.encodePacked can't contain variable length user input (SWC-133) // C12: abi.encodePacked has fixed length parameters bytes32 digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, DOMAIN_SEPARATOR, keccak256( abi.encode( APPROVAL_SIGNATURE_HASH, approved ? "Give FULL access to funds in (and approved to) SpellBook?" : "Revoke access to SpellBook?", user, masterContract, approved, nonces[user]++ ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress == user, "MasterCMgr: Invalid Signature"); } // Effects masterContractApproved[masterContract][user] = approved; emit LogSetMasterContractApproval(masterContract, user, approved); } } contract BasePossessedBatchable { function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, // each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall( calls[i] ); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } contract PossessedBatchable is BasePossessedBatchable { // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } // File contracts/SpellBook.sol // License-Identifier: UNLICENSED /// @title SpellBook /// @author thee Enchantress /// @notice The SpellBook is a vault for tokens. The stored tokens can be flash loaned and used in strategies. /// Yield from this will go to the token depositors. /// Rebasing tokens ARE NOT supported and WILL cause loss of funds. /// Any funds transfered directly onto the SpellBook will be lost, use the deposit function instead. contract SpellBook is MasterContractManager, PossessedBatchable { using PossessedMath for uint256; using PossessedMath128 for uint128; using PossessedERC20 for IERC20; using RebaseLibrary for Rebase; // ************** // // *** EVENTS *** // // ************** // event LogDeposit( IERC20 indexed token, address indexed from, address indexed to, uint256 amount, uint256 share ); event LogWithdraw( IERC20 indexed token, address indexed from, address indexed to, uint256 amount, uint256 share ); event LogTransfer( IERC20 indexed token, address indexed from, address indexed to, uint256 share ); event LogFlashLoan( address indexed borrower, IERC20 indexed token, uint256 amount, uint256 feeAmount, address indexed receiver ); event LogStrategyTargetPercentage( IERC20 indexed token, uint256 targetPercentage ); event LogStrategyQueued(IERC20 indexed token, IStrategy indexed strategy); event LogStrategySet(IERC20 indexed token, IStrategy indexed strategy); event LogStrategyInvest(IERC20 indexed token, uint256 amount); event LogStrategyDivest(IERC20 indexed token, uint256 amount); event LogStrategyProfit(IERC20 indexed token, uint256 amount); event LogStrategyLoss(IERC20 indexed token, uint256 amount); // *************** // // *** STRUCTS *** // // *************** // struct StrategyData { uint64 strategyStartDate; uint64 targetPercentage; uint128 balance; // the balance of the strategy that SpellBook thinks is in there } // ******************************** // // *** CONSTANTS AND IMMUTABLES *** // // ******************************** // // V2 - Can they be private? // V2: Private to save gas, to verify it's correct, check the constructor arguments IERC20 private immutable wethToken; IERC20 private constant USE_ETHEREUM = IERC20(address(0)); uint256 private constant FLASH_LOAN_FEE = 50; // 0.05% uint256 private constant FLASH_LOAN_FEE_PRECISION = 1e5; uint256 private constant STRATEGY_DELAY = 2 weeks; uint256 private constant MAX_TARGET_PERCENTAGE = 95; // 95% uint256 private constant MINIMUM_SHARE_BALANCE = 1000; // To prevent the ratio going off // ***************** // // *** VARIABLES *** // // ***************** // // Balance per token per address/contract in shares mapping(IERC20 => mapping(address => uint256)) public balanceOf; // Rebase from amount to share mapping(IERC20 => Rebase) public totals; mapping(IERC20 => IStrategy) public strategy; mapping(IERC20 => IStrategy) public pendingStrategy; mapping(IERC20 => StrategyData) public strategyData; // ******************* // // *** CONSTRUCTOR *** // // ******************* // constructor(IERC20 wethToken_) { wethToken = wethToken_; } // ***************** // // *** MODIFIERS *** // // ***************** // // Modifier to check if the msg.sender is allowed to use funds belonging to the 'from' address. // If 'from' is msg.sender, it's allowed. // If 'from' is the SpellBook itself, it's allowed. Any ETH, token balances // (above the known balances) or SpellBook balances can be taken by anyone. // This is to enable skimming, not just for deposits // but also for withdrawals or transfers, enabling better composability. // If 'from' is a clone of a masterContract AND the 'from' address has approved that masterContract, it's allowed. modifier allowed(address from) { if (from != msg.sender && from != address(this)) { // From is sender or you are skimming address masterContract = masterContractOf[msg.sender]; require( masterContract != address(0), "SpellBook: no masterContract" ); require( masterContractApproved[masterContract][from], "SpellBook: Transfer not approved" ); } _; } // ************************** // // *** INTERNAL FUNCTIONS *** // // ************************** // function _tokenBalanceOf(IERC20 token) internal view returns (uint256 amount) { amount = token.balanceOf(address(this)).add( strategyData[token].balance ); } // ************************ // // *** PUBLIC FUNCTIONS *** // // ************************ // /// @dev Helper function to represent an `amount` of `token` in shares. /// @param token The ERC-20 token. /// @param amount The `token` amount. /// @param roundUp If the result `share` should be rounded up. /// @return share The token amount represented in shares. function toShare( IERC20 token, uint256 amount, bool roundUp ) external view returns (uint256 share) { share = totals[token].toBase(amount, roundUp); } /// @dev Helper function represent shares back into the `token` amount. /// @param token The ERC-20 token. /// @param share The amount of shares. /// @param roundUp If the result should be rounded up. /// @return amount The share amount back into native representation. function toAmount( IERC20 token, uint256 share, bool roundUp ) external view returns (uint256 amount) { amount = totals[token].toElastic(share, roundUp); } /// @notice Deposit an amount of `token` represented in either `amount` or `share`. /// @param token_ The ERC-20 token to deposit. /// @param from which account to pull the tokens. /// @param to which account to push the tokens. /// @param amount Token amount in native representation to deposit. /// @param share Token amount represented in shares to deposit. Takes precedence over `amount`. /// @return amountOut The amount deposited. /// @return shareOut The deposited amount repesented in shares. function deposit( IERC20 token_, address from, address to, uint256 amount, uint256 share ) public payable allowed(from) returns (uint256 amountOut, uint256 shareOut) { // Checks require(to != address(0), "SpellBook: to not set"); // To avoid a bad UI from burning funds // Effects IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_; Rebase memory total = totals[token]; // If a new token gets added, the tokenSupply call checks that this is a deployed contract. Needed for security. require( total.elastic != 0 || token.totalSupply() > 0, "SpellBook: No tokens" ); if (share == 0) { // value of the share may be lower than the amount due to rounding, that's ok share = total.toBase(amount, false); // Any deposit should lead to at least the minimum share balance, otherwise it's ignored (no amount taken) if (total.base.add(share.to128()) < MINIMUM_SHARE_BALANCE) { return (0, 0); } } else { // amount may be lower than the value of share due to rounding // in that case, add 1 to amount (Always round up) amount = total.toElastic(share, true); } // In case of skimming, check that only the skimmable amount is taken. // For ETH, the full balance is available, so no need to check. // During flashloans the _tokenBalanceOf is lower than 'reality', // so skimming deposits will mostly fail during a flashloan. require( from != address(this) || token_ == USE_ETHEREUM || amount <= _tokenBalanceOf(token).sub(total.elastic), "SpellBook: Skim too much" ); balanceOf[token][to] = balanceOf[token][to].add(share); total.base = total.base.add(share.to128()); total.elastic = total.elastic.add(amount.to128()); totals[token] = total; // Interactions // During the first deposit, we check that this token is 'real' if (token_ == USE_ETHEREUM) { // X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113) // X2: If the WETH implementation is faulty or malicious, // it will block adding ETH (but we know the WETH implementation) IWETH(address(wethToken)).deposit{value: amount}(); } else if (from != address(this)) { // X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113) // X2: If the token implementation is faulty or malicious, it may block adding tokens. Good. token.safeTransferFrom(from, address(this), amount); } emit LogDeposit(token, from, to, amount, share); amountOut = amount; shareOut = share; } /// @notice Withdraws an amount of `token` from a user account. /// @param token_ The ERC-20 token to withdraw. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param amount of tokens. Either one of `amount` or `share` needs to be supplied. /// @param share Like above, but `share` takes precedence over `amount`. function withdraw( IERC20 token_, address from, address to, uint256 amount, uint256 share ) public allowed(from) returns (uint256 amountOut, uint256 shareOut) { // Checks require(to != address(0), "SpellBook: to not set"); // To avoid a bad UI from burning funds // Effects IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_; Rebase memory total = totals[token]; if (share == 0) { // value of the share paid could be lower than the amount paid due to rounding, // in that case, add a share (Always round up) share = total.toBase(amount, true); } else { // amount may be lower than the value of share due to rounding, that's ok amount = total.toElastic(share, false); } balanceOf[token][from] = balanceOf[token][from].sub(share); total.elastic = total.elastic.sub(amount.to128()); total.base = total.base.sub(share.to128()); // There have to be at least 1000 shares left to prevent resetting the share/amount ratio // (unless it's fully emptied) require( total.base >= MINIMUM_SHARE_BALANCE || total.base == 0, "SpellBook: cannot empty" ); totals[token] = total; // Interactions if (token_ == USE_ETHEREUM) { // X2, X3: A revert or big gas usage in the WETH contract could block withdrawals, but WETH9 is fine. IWETH(address(wethToken)).withdraw(amount); // X2, X3: A revert or big gas usage could block, however, the to address is under control of the caller. (bool success, ) = to.call{value: amount}(""); require(success, "SpellBook: ETH transfer failed"); } else { // X2, X3: A malicious token could block withdrawal of just THAT token. // masterContracts may want to take care not to rely on withdraw always succeeding. token.safeTransfer(to, amount); } emit LogWithdraw(token, from, to, amount, share); amountOut = amount; shareOut = share; } /// @notice Transfer shares from a user account to another one. /// @param token The ERC-20 token to transfer. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param share The amount of `token` in shares. // Clones of master contracts can transfer from any account that has approved them // F3 - Can it be combined with another similar function? // F3: This isn't combined with transferMultiple for gas optimization function transfer( IERC20 token, address from, address to, uint256 share ) public allowed(from) { // Checks require(to != address(0), "SpellBook: to not set"); // To avoid a bad UI from burning funds // Effects balanceOf[token][from] = balanceOf[token][from].sub(share); balanceOf[token][to] = balanceOf[token][to].add(share); emit LogTransfer(token, from, to, share); } /// @notice Transfer shares from a user account to multiple other ones. /// @param token The ERC-20 token to transfer. /// @param from which user to pull the tokens. /// @param tos The receivers of the tokens. /// @param shares The amount of `token` in shares for each receiver in `tos`. // F3 - Can it be combined with another similar function? // F3: This isn't combined with transfer for gas optimization function transferMultiple( IERC20 token, address from, address[] calldata tos, uint256[] calldata shares ) public allowed(from) { // Checks require(tos[0] != address(0), "SpellBook: to[0] not set"); // To avoid a bad UI from burning funds // Effects uint256 totalAmount; uint256 len = tos.length; for (uint256 i = 0; i < len; i++) { address to = tos[i]; balanceOf[token][to] = balanceOf[token][to].add(shares[i]); totalAmount = totalAmount.add(shares[i]); emit LogTransfer(token, from, to, shares[i]); } balanceOf[token][from] = balanceOf[token][from].sub(totalAmount); } /// @notice Flashloan ability. /// @param borrower The address of the contract that implements // and conforms to `IFlashBorrower` and handles the flashloan. /// @param receiver Address of the token receiver. /// @param token The address of the token to receive. /// @param amount of the tokens to receive. /// @param data The calldata to pass to the `borrower` contract. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Not possible to follow this here, reentrancy has been reviewed // F6 - Check for front-running possibilities, such as the approve function (SWC-114) // F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount. function flashLoan( IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data ) public { uint256 fee = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION; token.safeTransfer(receiver, amount); borrower.onFlashLoan(msg.sender, token, amount, fee, data); require( _tokenBalanceOf(token) >= totals[token].addElastic(fee.to128()), "SpellBook: Wrong amount" ); emit LogFlashLoan(address(borrower), token, amount, fee, receiver); } /// @notice Support for batched flashloans. Useful to request multiple different `tokens` in a single transaction. /// @param borrower The address of the contract that implements // and conforms to `IBatchFlashBorrower` and handles the flashloan. /// @param receivers An array of the token receivers. A one-to-one mapping with `tokens` and `amounts`. /// @param tokens The addresses of the tokens. /// @param amounts of the tokens for each receiver. /// @param data The calldata to pass to the `borrower` contract. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Not possible to follow this here, reentrancy has been reviewed // F6 - Check for front-running possibilities, such as the approve function (SWC-114) // F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount. function batchFlashLoan( IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data ) public { uint256[] memory fees = new uint256[](tokens.length); uint256 len = tokens.length; for (uint256 i = 0; i < len; i++) { uint256 amount = amounts[i]; fees[i] = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION; tokens[i].safeTransfer(receivers[i], amounts[i]); } borrower.onBatchFlashLoan(msg.sender, tokens, amounts, fees, data); for (uint256 i = 0; i < len; i++) { IERC20 token = tokens[i]; require( _tokenBalanceOf(token) >= totals[token].addElastic(fees[i].to128()), "SpellBook: Wrong amount" ); emit LogFlashLoan( address(borrower), token, amounts[i], fees[i], receivers[i] ); } } /// @notice Sets the target percentage of the strategy for `token`. /// @dev Only the owner of this contract is allowed to change this. /// @param token The address of the token that maps to a strategy to change. /// @param targetPercentage_ The new target in percent. Must be lesser or equal to `MAX_TARGET_PERCENTAGE`. function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) public onlyOwner { // Checks require( targetPercentage_ <= MAX_TARGET_PERCENTAGE, "StrategyManager: Target too high" ); // Effects strategyData[token].targetPercentage = targetPercentage_; emit LogStrategyTargetPercentage(token, targetPercentage_); } /// @notice Sets the contract address of a new strategy that conforms to `IStrategy` for `token`. /// Must be called twice with the same arguments. /// A new strategy becomes pending first and can be activated once `STRATEGY_DELAY` is over. /// @dev Only the owner of this contract is allowed to change this. /// @param token The address of the token that maps to a strategy to change. /// @param newStrategy The address of the contract that conforms to `IStrategy`. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Total amount is updated AFTER interaction. But strategy is under our control. // C4 - Use block.timestamp only for long intervals (SWC-116) // C4: block.timestamp is used for a period of 2 weeks, which is long enough function setStrategy(IERC20 token, IStrategy newStrategy) public onlyOwner { StrategyData memory data = strategyData[token]; IStrategy pending = pendingStrategy[token]; if (data.strategyStartDate == 0 || pending != newStrategy) { pendingStrategy[token] = newStrategy; // C1 - All math done through PossessedMath (SWC-101) // C1: Our sun will swallow the earth well before this overflows data.strategyStartDate = (block.timestamp + STRATEGY_DELAY).to64(); emit LogStrategyQueued(token, newStrategy); } else { require( data.strategyStartDate != 0 && block.timestamp >= data.strategyStartDate, "StrategyManager: Too early" ); if (address(strategy[token]) != address(0)) { int256 balanceChange = strategy[token].exit(data.balance); // Effects if (balanceChange > 0) { uint256 add = uint256(balanceChange); totals[token].addElastic(add); emit LogStrategyProfit(token, add); } else if (balanceChange < 0) { uint256 sub = uint256(-balanceChange); totals[token].subElastic(sub); emit LogStrategyLoss(token, sub); } emit LogStrategyDivest(token, data.balance); } strategy[token] = pending; data.strategyStartDate = 0; data.balance = 0; pendingStrategy[token] = IStrategy(address(0)); emit LogStrategySet(token, newStrategy); } strategyData[token] = data; } /// @notice The actual process of yield farming. Executes the strategy of `token`. /// Optionally does housekeeping if `balance` is true. /// `maxChangeAmount` is relevant for skimming or withdrawing if `balance` is true. /// @param token The address of the token for which a strategy is deployed. /// @param balance True if housekeeping should be done. /// @param maxChangeAmount The maximum amount for either pulling or pushing from/to the `IStrategy` contract. // F5 - Checks-Effects-Interactions pattern followed? (SWC-107) // F5: Total amount is updated AFTER interaction. But strategy is under our control. // F5: Not followed to prevent reentrancy issues with flashloans and SpellBook skims? function harvest( IERC20 token, bool balance, uint256 maxChangeAmount ) public { StrategyData memory data = strategyData[token]; IStrategy _strategy = strategy[token]; int256 balanceChange = _strategy.harvest(data.balance, msg.sender); if (balanceChange == 0 && !balance) { return; } uint256 totalElastic = totals[token].elastic; if (balanceChange > 0) { uint256 add = uint256(balanceChange); totalElastic = totalElastic.add(add); totals[token].elastic = totalElastic.to128(); emit LogStrategyProfit(token, add); } else if (balanceChange < 0) { // C1 - All math done through PossessedMath (SWC-101) // C1: balanceChange could overflow if it's max negative int128. // But tokens with balances that large are not supported by the SpellBook. uint256 sub = uint256(-balanceChange); totalElastic = totalElastic.sub(sub); totals[token].elastic = totalElastic.to128(); data.balance = data.balance.sub(sub.to128()); emit LogStrategyLoss(token, sub); } if (balance) { uint256 targetBalance = totalElastic.mul(data.targetPercentage) / 100; // if data.balance == targetBalance there is nothing to update if (data.balance < targetBalance) { uint256 amountOut = targetBalance.sub(data.balance); if (maxChangeAmount != 0 && amountOut > maxChangeAmount) { amountOut = maxChangeAmount; } token.safeTransfer(address(_strategy), amountOut); data.balance = data.balance.add(amountOut.to128()); _strategy.skim(amountOut); emit LogStrategyInvest(token, amountOut); } else if (data.balance > targetBalance) { uint256 amountIn = data.balance.sub(targetBalance.to128()); if (maxChangeAmount != 0 && amountIn > maxChangeAmount) { amountIn = maxChangeAmount; } uint256 actualAmountIn = _strategy.withdraw(amountIn); data.balance = data.balance.sub(actualAmountIn.to128()); emit LogStrategyDivest(token, actualAmountIn); } } strategyData[token] = data; } // Contract should be able to receive ETH deposits to support deposit & skim // solhint-disable-next-line no-empty-blocks receive() external payable {} }
F4 - Check behaviour for all function arguments when wrong or extreme F4: Don't allow masterContract 0 to be approved. Unknown contracts will have a masterContract of 0. F4: User can't be 0 for signed approvals because the recoveredAddress will be 0 if ecrecover fails Checks If no signature is provided, the fallback is executed Important for security - any address without masterContract has address(0) as masterContract So approving address(0) would approve every address, leading to full loss of funds Also, ecrecover returns address(0) on failure. So we check this: C10 - Protect signatures against replay, use nonce and chainId (SWC-121) C10: nonce + chainId are used to prevent replays C11 - All signatures strictly EIP-712 (SWC-117 SWC-122) C11: signature is EIP-712 compliant C12 - abi.encodePacked can't contain variable length user input (SWC-133) C12: abi.encodePacked has fixed length parameters
function setMasterContractApproval( address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) public { if (r == 0 && s == 0 && v == 0) { require(user == msg.sender, "MasterCMgr: user not sender"); require( masterContractOf[user] == address(0), "MasterCMgr: user is clone" ); require( whitelistedMasterContracts[masterContract], "MasterCMgr: not whitelisted" ); require(user != address(0), "MasterCMgr: User cannot be 0"); bytes32 digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, DOMAIN_SEPARATOR, keccak256( abi.encode( APPROVAL_SIGNATURE_HASH, approved ? "Give FULL access to funds in (and approved to) SpellBook?" : "Revoke access to SpellBook?", user, masterContract, approved, nonces[user]++ ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress == user, "MasterCMgr: Invalid Signature"); } emit LogSetMasterContractApproval(masterContract, user, approved); }
14,064,557
pragma solidity 0.5.12; import { Context } from "@openzeppelin/contracts/GSN/Context.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC777 } from "@openzeppelin/contracts/token/ERC777/IERC777.sol"; import { IERC777Recipient } from "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import { IERC777Sender } from "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { IERC1820Registry } from "@openzeppelin/contracts/introspection/IERC1820Registry.sol"; import { RuntimeConstants } from "./RuntimeConstants.sol"; // ERC777 is inlined because we need to change `_callTokensToSend` to protect against Uniswap replay attacks /** * @dev Implementation of the {IERC777} 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}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is RuntimeConstants, Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; // KEYDONIX: Protect against Uniswap Exchange reentrancy bug: https://blog.openzeppelin.com/exploiting-uniswap-from-reentrancy-to-actual-profit/ bool uniswapExchangeReentrancyGuard = false; /** * @dev `defaultOperators` may be an empty array. */ constructor(string memory name, string memory symbol, address[] memory defaultOperators) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(_msgSender(), _msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes calldata data) external { _burn(_msgSender(), _msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend(address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(_msgSender(), sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(_msgSender(), account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); // KEYDONIX: Block re-entrancy specifically for uniswap, which is vulnerable to ERC-777 tokens if (msg.sender == uniswapExchange) { require(!uniswapExchangeReentrancyGuard, "Attempted to execute a Uniswap exchange while in the middle of a Uniswap exchange"); uniswapExchangeReentrancyGuard = true; } _callTokensToSend(spender, holder, recipient, amount, "", ""); if (msg.sender == uniswapExchange) { uniswapExchangeReentrancyGuard = false; } _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint(address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData) internal { require(account != address(0), "ERC777: mint to the zero address"); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } // KEYDONIX: changed visibility from private to internal, we reference this function in derived contract /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // KEYDONIX: changed visibility from private to internal, we reference this function in derived contract /** * @dev Burn tokens * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn(address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData) internal { require(from != address(0), "ERC777: burn from the zero address"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData) private { _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) private { // TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is // currently unnecessary. //require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData) private { address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck) private { address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } } contract MakerFunctions { // KEYDONIX: Renamed from `rmul` for clarity // KEYDONIX: Changed ONE to 10**27 for clarity function safeMul27(uint x, uint y) internal pure returns (uint z) { z = safeMul(x, y) / 10 ** 27; } function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } // KEYDONIX: Renamed from `mul` due to shadowing warning from Solidity function safeMul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } } contract ReverseRegistrar { function setName(string memory name) public returns (bytes32 node); } contract DaiHrd is ERC777, MakerFunctions { event Deposit(address indexed from, uint256 depositedAttodai, uint256 mintedAttodaiHrd); event Withdrawal(address indexed from, address indexed to, uint256 withdrawnAttodai, uint256 burnedAttodaiHrd); event DepositVatDai(address indexed account, uint256 depositedAttorontodai, uint256 mintedAttodaiHrd); event WithdrawalVatDai(address indexed from, address indexed to, uint256 withdrawnAttorontodai, uint256 burnedAttodaiHrd); // uses this super constructor syntax instead of the preferred alternative syntax because my editor doesn't like the class syntax constructor(ReverseRegistrar reverseRegistrar) ERC777("DAI-HRD", "DAI-HRD", new address[](0)) public { dai.approve(address(daiJoin), uint(-1)); vat.hope(address(pot)); vat.hope(address(daiJoin)); if (reverseRegistrar != ReverseRegistrar(0)) { reverseRegistrar.setName("dai-hrd.eth"); } } function deposit(uint256 attodai) external returns(uint256 attodaiHrd) { dai.transferFrom(msg.sender, address(this), attodai); daiJoin.join(address(this), dai.balanceOf(address(this))); uint256 depositedAttopot = depositVatDaiForAccount(msg.sender); emit Deposit(msg.sender, attodai, depositedAttopot); return depositedAttopot; } // If the user has vat dai directly (after performing vault actions, for instance), they don't need to create the DAI ERC20 just so we can burn it, we'll accept vat dai function depositVatDai(uint256 attorontovatDai) external returns(uint256 attodaiHrd) { vat.move(msg.sender, address(this), attorontovatDai); uint256 depositedAttopot = depositVatDaiForAccount(msg.sender); emit DepositVatDai(msg.sender, attorontovatDai, depositedAttopot); return depositedAttopot; } function withdrawTo(address recipient, uint256 attodaiHrd) external returns(uint256 attodai) { // Don't need rontodaiPerPot, so we don't call updateAndFetchChi if (pot.rho() != now) pot.drip(); return withdraw(recipient, attodaiHrd); } function withdrawToDenominatedInDai(address recipient, uint256 attodai) external returns(uint256 attodaiHrd) { uint256 rontodaiPerPot = updateAndFetchChi(); attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); uint256 attodaiWithdrawn = withdraw(recipient, attodaiHrd); require(attodaiWithdrawn >= attodai, "DaiHrd/withdrawToDenominatedInDai: Not withdrawing enough DAI to cover request"); return attodaiHrd; } function withdrawVatDai(address recipient, uint256 attodaiHrd) external returns(uint256 attorontodai) { require(recipient != address(0) && recipient != address(this), "DaiHrd/withdrawVatDai: Invalid recipient"); // Don't need rontodaiPerPot, so we don't call updateAndFetchChi if (pot.rho() != now) pot.drip(); _burn(address(0), msg.sender, attodaiHrd, new bytes(0), new bytes(0)); pot.exit(attodaiHrd); attorontodai = vat.dai(address(this)); vat.move(address(this), recipient, attorontodai); emit WithdrawalVatDai(msg.sender, recipient, attorontodai, attodaiHrd); return attorontodai; } // Dai specific functions. These functions all behave similar to standard ERC777 functions with input or output denominated in Dai instead of DaiHrd function balanceOfDenominatedInDai(address tokenHolder) external view returns(uint256 attodai) { uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = balanceOf(tokenHolder); return convertAttodaiHrdToAttodai(attodaiHrd, rontodaiPerPot); } function totalSupplyDenominatedInDai() external view returns(uint256 attodai) { uint256 rontodaiPerPot = calculatedChi(); return convertAttodaiHrdToAttodai(totalSupply(), rontodaiPerPot); } function sendDenominatedInDai(address recipient, uint256 attodai, bytes calldata data) external { uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _send(_msgSender(), _msgSender(), recipient, attodaiHrd, data, "", true); } function burnDenominatedInDai(uint256 attodai, bytes calldata data) external { uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _burn(_msgSender(), _msgSender(), attodaiHrd, data, ""); } function operatorSendDenominatedInDai(address sender, address recipient, uint256 attodai, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _send(_msgSender(), sender, recipient, attodaiHrd, data, operatorData, true); } function operatorBurnDenominatedInDai(address account, uint256 attodai, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _burn(_msgSender(), account, attodaiHrd, data, operatorData); } // Utility Functions function calculatedChi() public view returns (uint256 rontodaiPerPot) { // mirrors Maker's calculation: rmul(rpow(dsr, now - rho, ONE), chi); return safeMul27(rpow(pot.dsr(), now - pot.rho(), 10 ** 27), pot.chi()); } function convertAttodaiToAttodaiHrd(uint256 attodai, uint256 rontodaiPerPot ) private pure returns (uint256 attodaiHrd) { // + 1 is to compensate rounding? since attodaiHrd is rounded down return attodai.mul(10 ** 27).add(rontodaiPerPot - 1).div(rontodaiPerPot); } function convertAttodaiHrdToAttodai(uint256 attodaiHrd, uint256 rontodaiPerPot ) private pure returns (uint256 attodai) { return attodaiHrd.mul(rontodaiPerPot).div(10 ** 27); } function updateAndFetchChi() private returns (uint256 rontodaiPerPot) { return (pot.rho() == now) ? pot.chi() : pot.drip(); } // Takes whatever vat dai has already been transferred to DaiHrd, gives to pot (DSR) and mints tokens for user function depositVatDaiForAccount(address account) private returns (uint256 attopotDeposited) { uint256 rontodaiPerPot = updateAndFetchChi(); uint256 attopotToDeposit = vat.dai(address(this)) / rontodaiPerPot; pot.join(attopotToDeposit); _mint(address(0), account, attopotToDeposit, new bytes(0), new bytes(0)); return attopotToDeposit; } // Internal implementations of functions with multiple entrypoints. drip() should be called prior to this call function withdraw(address recipient, uint256 attodaiHrd) private returns(uint256 attodaiWithdrawn) { require(recipient != address(0) && recipient != address(this), "DaiHrd/withdraw: Invalid recipient"); _burn(address(0), msg.sender, attodaiHrd, new bytes(0), new bytes(0)); pot.exit(attodaiHrd); daiJoin.exit(address(this), vat.dai(address(this)) / 10**27); uint256 attodai = dai.balanceOf(address(this)); dai.transfer(recipient, attodai); emit Withdrawal(msg.sender, recipient, attodai, attodaiHrd); return attodai; } }
Creates `amount` tokens and assigns them to `account`, increasing the total supply. If a send hook is registered for `account`, the corresponding function will be called with `operator`, `data` and `operatorData`. See {IERC777Sender} and {IERC777Recipient}. Emits {Minted} and {Transfer} events. Requirements - `account` cannot be the zero address. - if `account` is a contract, it must implement the {IERC777Recipient} interface./ Update state variables
function _mint(address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData) internal { require(account != address(0), "ERC777: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); }
2,521,562
/** * The edgeless casino contract holds the players's funds and provides state channel functionality. * The casino has at no time control over the players's funds. * State channels can be updated and closed from both parties: the player and the casino. * author: Julia Altenried **/ pragma solidity ^0.4.17; contract SafeMath { function safeSub(uint a, uint b) pure internal returns(uint) { assert(b <= a); return a - b; } function safeSub(int a, int b) pure internal returns(int) { if(b < 0) assert(a - b > a); else assert(a - b <= a); return a - b; } function safeAdd(uint a, uint b) pure internal returns(uint) { uint c = a + b; assert(c >= a && c >= b); return c; } function safeMul(uint a, uint b) pure internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } } contract owned { address public owner; modifier onlyOwner { require(msg.sender == owner); _; } function owned() public{ owner = msg.sender; } function changeOwner(address newOwner) onlyOwner public{ owner = newOwner; } } /** owner should be able to close the contract is nobody has been using it for at least 30 days */ contract mortal is owned { /** contract can be closed by the owner anytime after this timestamp if non-zero */ uint public closeAt; /** * lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days */ function closeContract(uint playerBalance) internal{ if(playerBalance == 0) selfdestruct(owner); if(closeAt == 0) closeAt = now + 30 days; else if(closeAt < now) selfdestruct(owner); } /** * in case close has been called accidentally. **/ function open() onlyOwner public{ closeAt = 0; } /** * make sure the contract is not in process of being closed. **/ modifier isAlive { require(closeAt == 0); _; } /** * delays the time of closing. **/ modifier keepAlive { if(closeAt > 0) closeAt = now + 30 days; _; } } contract chargingGas is mortal, SafeMath{ /** the price per kgas and GWei in tokens (5 decimals) */ uint public gasPrice; /** the amount of gas used per transaction in kGas */ mapping(bytes4 => uint) public gasPerTx; /** * sets the amount of gas consumed by methods with the given sigantures. * only called from the edgeless casino constructor. * @param signatures an array of method-signatures * gasNeeded the amount of gas consumed by these methods * */ function setGasUsage(bytes4[3] signatures, uint[3] gasNeeded) internal{ require(signatures.length == gasNeeded.length); for(uint8 i = 0; i < signatures.length; i++) gasPerTx[signatures[i]] = gasNeeded[i]; } /** * adds the gas cost of the tx to the given value. * @param value the value to add the gas cost to * */ function addGas(uint value) internal constant returns(uint){ return safeAdd(value,getGasCost()); } /** * subtracts the gas cost of the tx from the given value. * @param value the value to subtract the gas cost from * */ function subtractGas(uint value) internal constant returns(uint){ return safeSub(value,getGasCost()); } /** * updates the price per 1000 gas in EDG. * @param price the new gas price (4 decimals, max 0.0256 EDG) **/ function setGasPrice(uint8 price) public onlyOwner{ gasPrice = price; } /** * returns the gas cost of the called function. * */ function getGasCost() internal constant returns(uint){ return safeMul(safeMul(gasPerTx[msg.sig], gasPrice), tx.gasprice)/1000000000; } } contract Token { function transferFrom(address sender, address receiver, uint amount) public returns(bool success) {} function transfer(address receiver, uint amount) public returns(bool success) {} function balanceOf(address holder) public constant returns(uint) {} } contract CasinoBank is chargingGas{ /** the total balance of all players with 5 virtual decimals **/ uint public playerBalance; /** the balance per player in edgeless tokens with 5 virtual decimals */ mapping(address=>uint) public balanceOf; /** in case the user wants/needs to call the withdraw function from his own wallet, he first needs to request a withdrawal */ mapping(address=>uint) public withdrawAfter; /** the edgeless token contract */ Token edg; /** the maximum amount of tokens the user is allowed to deposit (5 decimals) */ uint public maxDeposit; /** waiting time for withdrawal if not requested via the server **/ uint public waitingTime; /** informs listeners how many tokens were deposited for a player */ event Deposit(address _player, uint _numTokens, bool _chargeGas); /** informs listeners how many tokens were withdrawn from the player to the receiver address */ event Withdrawal(address _player, address _receiver, uint _numTokens); function CasinoBank(address tokenContract, uint depositLimit) public{ edg = Token(tokenContract); maxDeposit = depositLimit; waitingTime = 90 minutes; } /** * accepts deposits for an arbitrary address. * retrieves tokens from the message sender and adds them to the balance of the specified address. * edgeless tokens do not have any decimals, but are represented on this contract with 5 decimals. * @param receiver address of the receiver * numTokens number of tokens to deposit (0 decimals) * chargeGas indicates if the gas cost is subtracted from the user's edgeless token balance **/ function deposit(address receiver, uint numTokens, bool chargeGas) public isAlive{ require(numTokens > 0); uint value = safeMul(numTokens,100000); if(chargeGas) value = subtractGas(value); uint newBalance = safeAdd(balanceOf[receiver], value); require(newBalance <= maxDeposit); assert(edg.transferFrom(msg.sender, address(this), numTokens)); balanceOf[receiver] = newBalance; playerBalance = safeAdd(playerBalance, value); Deposit(receiver, numTokens, chargeGas); } /** * If the user wants/needs to withdraw his funds himself, he needs to request the withdrawal first. * This method sets the earliest possible withdrawal date to 'waitingTime from now (default 90m, but up to 24h). * Reason: The user should not be able to withdraw his funds, while the the last game methods have not yet been mined. **/ function requestWithdrawal() public{ withdrawAfter[msg.sender] = now + waitingTime; } /** * In case the user requested a withdrawal and changes his mind. * Necessary to be able to continue playing. **/ function cancelWithdrawalRequest() public{ withdrawAfter[msg.sender] = 0; } /** * withdraws an amount from the user balance if the waiting time passed since the request. * @param amount the amount of tokens to withdraw **/ function withdraw(uint amount) public keepAlive{ require(withdrawAfter[msg.sender]>0 && now>withdrawAfter[msg.sender]); withdrawAfter[msg.sender] = 0; uint value = safeMul(amount,100000); balanceOf[msg.sender]=safeSub(balanceOf[msg.sender],value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(msg.sender, amount)); Withdrawal(msg.sender, msg.sender, amount); } /** * lets the owner withdraw from the bankroll * @param numTokens the number of tokens to withdraw (0 decimals) **/ function withdrawBankroll(uint numTokens) public onlyOwner { require(numTokens <= bankroll()); assert(edg.transfer(owner, numTokens)); } /** * returns the current bankroll in tokens with 0 decimals **/ function bankroll() constant public returns(uint){ return safeSub(edg.balanceOf(address(this)), playerBalance/100000); } /** * updates the maximum deposit. * @param newMax the new maximum deposit (5 decimals) **/ function setMaxDeposit(uint newMax) public onlyOwner{ maxDeposit = newMax; } /** * sets the time the player has to wait for his funds to be unlocked before withdrawal (if not withdrawing with help of the casino server). * the time may not be longer than 24 hours. * @param newWaitingTime the new waiting time in seconds * */ function setWaitingTime(uint newWaitingTime) public onlyOwner{ require(newWaitingTime <= 24 hours); waitingTime = newWaitingTime; } /** * lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days * */ function close() public onlyOwner{ closeContract(playerBalance); } } contract EdgelessCasino is CasinoBank{ /** indicates if an address is authorized to act in the casino's name */ mapping(address => bool) public authorized; /** a number to count withdrawal signatures to ensure each signature is different even if withdrawing the same amount to the same address */ mapping(address => uint) public withdrawCount; /** the most recent known state of a state channel */ mapping(address => State) public lastState; /** fired when the state is updated */ event StateUpdate(uint128 count, int128 winBalance, int difference, uint gasCost, address player, uint128 lcount); /** fired if one of the parties chooses to log the seeds and results */ event GameData(address player, bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results); struct State{ uint128 count; int128 winBalance; } modifier onlyAuthorized { require(authorized[msg.sender]); _; } /** * creates a new edgeless casino contract. * @param authorizedAddress the address which may send transactions to the Edgeless Casino * tokenContract the address of the Edgeless token contract * depositLimit the maximum deposit allowed * kGasPrice the price per kGas in WEI **/ function EdgelessCasino(address authorizedAddress, address tokenContract, uint depositLimit, uint8 kGasPrice) CasinoBank(tokenContract, depositLimit) public{ authorized[authorizedAddress] = true; //deposit, withdrawFor, updateChannel bytes4[3] memory signatures = [bytes4(0x3edd1128),0x9607610a, 0x713d30c6]; //amount of gas consumed by the above methods in GWei uint[3] memory gasUsage = [uint(85),95,60]; setGasUsage(signatures, gasUsage); setGasPrice(kGasPrice); } /** * transfers an amount from the contract balance to the owner's wallet. * @param receiver the receiver address * amount the amount of tokens to withdraw (0 decimals) * v,r,s the signature of the player **/ function withdrawFor(address receiver, uint amount, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized keepAlive{ var player = ecrecover(keccak256(receiver, amount, withdrawCount[receiver]), v, r, s); withdrawCount[receiver]++; uint value = addGas(safeMul(amount,100000)); balanceOf[player] = safeSub(balanceOf[player], value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(receiver, amount)); Withdrawal(player, receiver, amount); } /** * authorize a address to call game functions. * @param addr the address to be authorized **/ function authorize(address addr) public onlyOwner{ authorized[addr] = true; } /** * deauthorize a address to call game functions. * @param addr the address to be deauthorized **/ function deauthorize(address addr) public onlyOwner{ authorized[addr] = false; } /** * closes a state channel. can also be used for intermediate state updates. can be called by both parties. * 1. verifies the signature. * 2. verifies if the signed game-count is higher than the last known game-count of this channel. * 3. updates the balances accordingly. This means: It checks the already performed updates for this channel and computes * the new balance difference to add or subtract from the player‘s balance. * @param winBalance the current win or loss * gameCount the number of signed game moves * v,r,s the signature of either the casino or the player * */ function updateState(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s) public{ address player = determinePlayer(winBalance, gameCount, v, r, s); uint gasCost = 0; if(player == msg.sender)//if the player closes the state channel himself, make sure the signer is a casino wallet require(authorized[ecrecover(keccak256(player, winBalance, gameCount), v, r, s)]); else//if the casino wallet is the sender, subtract the gas costs from the player balance gasCost = getGasCost(); State storage last = lastState[player]; require(gameCount > last.count); int difference = updatePlayerBalance(player, winBalance, last.winBalance, gasCost); lastState[player] = State(gameCount, winBalance); StateUpdate(gameCount, winBalance, difference, gasCost, player, last.count); } /** * determines if the msg.sender or the signer of the passed signature is the player. returns the player's address * @param winBalance the current winBalance, used to calculate the msg hash * gameCount the current gameCount, used to calculate the msg.hash * v, r, s the signature of the non-sending party * */ function determinePlayer(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s) constant internal returns(address){ if (authorized[msg.sender])//casino is the sender -> player is the signer return ecrecover(keccak256(winBalance, gameCount), v, r, s); else return msg.sender; } /** * computes the difference of the win balance relative to the last known state and adds it to the player's balance. * in case the casino is the sender, the gas cost in EDG gets subtracted from the player's balance. * @param player the address of the player * winBalance the current win-balance * lastWinBalance the win-balance of the last known state * gasCost the gas cost of the tx * */ function updatePlayerBalance(address player, int128 winBalance, int128 lastWinBalance, uint gasCost) internal returns(int difference){ difference = safeSub(winBalance, lastWinBalance); int outstanding = safeSub(difference, int(gasCost)); uint outs; if(outstanding < 0){ outs = uint256(outstanding * (-1)); playerBalance = safeSub(playerBalance, outs); balanceOf[player] = safeSub(balanceOf[player], outs); } else{ outs = uint256(outstanding); playerBalance = safeAdd(playerBalance, outs); balanceOf[player] = safeAdd(balanceOf[player], outs); } } /** * logs some seeds and game results for players wishing to have their game history logged by the contract * @param serverSeeds array containing the server seeds * clientSeeds array containing the client seeds * results array containing the results * v, r, s the signature of the non-sending party (to make sure the corrcet results are logged) * */ function logGameData(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) public{ address player = determinePlayer(serverSeeds, clientSeeds, results, v, r, s); GameData(player, serverSeeds, clientSeeds, results); //charge gas in case the server is logging the results for the player if(player != msg.sender){ uint gasCost = (57 + 768 * serverSeeds.length / 1000)*gasPrice; balanceOf[player] = safeSub(balanceOf[player], gasCost); playerBalance = safeSub(playerBalance, gasCost); } } /** * determines if the msg.sender or the signer of the passed signature is the player. returns the player's address * @param serverSeeds array containing the server seeds * clientSeeds array containing the client seeds * results array containing the results * v, r, s the signature of the non-sending party * */ function determinePlayer(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) constant internal returns(address){ if (authorized[msg.sender])//casino is the sender -> player is the signer return ecrecover(keccak256(serverSeeds, clientSeeds, results), v, r, s); else return msg.sender; } }
determines if the msg.sender or the signer of the passed signature is the player. returns the player's address winBalance the current winBalance, used to calculate the msg hash gameCount the current gameCount, used to calculate the msg.hash v, r, s the signature of the non-sending party /
function determinePlayer(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s) constant internal returns(address){ return ecrecover(keccak256(winBalance, gameCount), v, r, s); else return msg.sender; }
12,781,963
./full_match/80001/0xaaE660f00db52D912173E9aEa1Af1e33fe9422C1/sources/contracts/Vault.sol
Returns true if withdrawl signature has been processed _signature Signature to check
function checkWithdrawalSignature( bytes calldata _signature ) public view virtual returns (bool) { return _seenWithdrawalSignatures[_signature]; }
852,197
// Sources flattened with hardhat v2.6.8 https://hardhat.org // SPDX-License-Identifier: MIT // File @openzeppelin/contracts/utils/[email protected] 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; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.7.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 @openzeppelin/contracts/math/[email protected] pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.7.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/[email protected] pragma solidity ^0.7.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/interfaces/IStaking.sol pragma solidity ^0.7.6; interface IStaking { function stake(uint256 _amount) external; function stakeFor(address _recipient, uint256 _amount) external; function unstake(address _recipient, uint256 _amount) external; function unstakeAll(address _recipient) external; function bondFor(address _recipient, uint256 _amount) external; function rewardBond(address _vault, uint256 _amount) external; function rebase() external; function redeem(address _recipient, bool _withdraw) external; } // File contracts/interfaces/ITreasury.sol pragma solidity ^0.7.6; interface ITreasury { enum ReserveType { // used by reserve manager, will not used to bond ALD. NULL, // used by main asset bond UNDERLYING, // used by vault reward bond VAULT_REWARD, // used by liquidity token bond LIQUIDITY_TOKEN } /// @dev return the usd value given token and amount. /// @param _token The address of token. /// @param _amount The amount of token. function valueOf(address _token, uint256 _amount) external view returns (uint256); /// @dev return the amount of bond ALD given token and usd value. /// @param _token The address of token. /// @param _value The usd of token. function bondOf(address _token, uint256 _value) external view returns (uint256); /// @dev deposit token to bond ALD. /// @param _type The type of deposited token. /// @param _token The address of token. /// @param _amount The amount of token. function deposit( ReserveType _type, address _token, uint256 _amount ) external returns (uint256); /// @dev withdraw token from POL. /// @param _token The address of token. /// @param _amount The amount of token. function withdraw(address _token, uint256 _amount) external; /// @dev manage token to earn passive yield. /// @param _token The address of token. /// @param _amount The amount of token. function manage(address _token, uint256 _amount) external; /// @dev mint ALD reward. /// @param _recipient The address of to receive ALD token. /// @param _amount The amount of token. function mintRewards(address _recipient, uint256 _amount) external; } // File contracts/interfaces/IUniswapV2Pair.sol pragma solidity ^0.7.6; interface IUniswapV2Pair { function totalSupply() external view returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); } // File contracts/bond/DirectBondDepositor.sol pragma solidity ^0.7.6; contract DirectBondDepositor is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; event Deposit(address indexed caller, address indexed token, uint256 amount); event UpdateBondAsset(address indexed token, bool status); event AddLiquidityToken(address indexed token); // The address of ald. address public immutable ald; // The address of Treasury. address public immutable treasury; // The address of Staking. address public staking; // Record whether an asset can be used to bond ALD. mapping(address => bool) public isBondAsset; // Record whether an asset is liquidity token. mapping(address => bool) public isLiquidityToken; // Mapping from asset address to total deposited amount. mapping(address => uint256) public totalPurchased; // The address of initializer to initialize staking address. address private _initializer; /// @param _ald The address of ALD token. /// @param _treasury The address of treasury. constructor(address _ald, address _treasury) { require(_ald != address(0), "DirectBondDepositor: not zero address"); require(_treasury != address(0), "DirectBondDepositor: not zero address"); ald = _ald; treasury = _treasury; _initializer = msg.sender; } /// @dev initialize staking address. Can only be called once. /// @param _staking The address of staking contract. function initialize(address _staking) external { require(_initializer == msg.sender, "DirectBondDepositor: only initializer"); require(_staking != address(0), "DirectBondDepositor: not zero address"); IERC20(ald).safeApprove(_staking, uint256(-1)); staking = _staking; _initializer = address(0); } /********************************** View Functions **********************************/ /// @dev return the amount of ALD could bond given token and amount. /// @param _token The address of token. /// @param _amount The amount of token. function getBondALD(address _token, uint256 _amount) external view returns (uint256) { if (!isBondAsset[_token]) return 0; uint256 _value = ITreasury(treasury).valueOf(_token, _amount); return ITreasury(treasury).bondOf(_token, _value); } /********************************** Mutated Functions **********************************/ /// @dev deposit token to bond ALD. /// @param _token The address of token. /// @param _amount The amount of token. function deposit( address _token, uint256 _amount, uint256 _minBondAmount ) external nonReentrant { require(tx.origin == msg.sender, "DirectBondDepositor: only EOA"); require(isBondAsset[_token], "DirectBondDepositor: not approved"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); totalPurchased[_token] = totalPurchased[_token].add(_amount); uint256 _bondAmount; if (isLiquidityToken[_token]) { _bondAmount = ITreasury(treasury).deposit(ITreasury.ReserveType.LIQUIDITY_TOKEN, _token, _amount); } else { _bondAmount = ITreasury(treasury).deposit(ITreasury.ReserveType.UNDERLYING, _token, _amount); } require(_bondAmount >= _minBondAmount, "DirectBondDepositor: bond not enough"); IStaking(staking).bondFor(msg.sender, _bondAmount); emit Deposit(msg.sender, _token, _amount); } /********************************** Restricted Functions **********************************/ /// @dev update supported bond asset /// @param _token The address of token. /// @param _status Whether it is add or remove token. function updateBondAsset(address _token, bool _status) external onlyOwner { isBondAsset[_token] = _status; if (_status) { IERC20(_token).safeApprove(treasury, uint256(-1)); } else { IERC20(_token).safeApprove(treasury, 0); } emit UpdateBondAsset(_token, _status); } /// @dev add liquidity token to bond asset. /// @param _pair The address of token. function addLiquidityToken(address _pair) external onlyOwner { require( IUniswapV2Pair(_pair).token0() == ald || IUniswapV2Pair(_pair).token1() == ald, "DirectBondDepositor: not supported" ); isBondAsset[_pair] = true; isLiquidityToken[_pair] = true; IERC20(_pair).safeApprove(treasury, uint256(-1)); emit AddLiquidityToken(_pair); emit UpdateBondAsset(_pair, true); } }
initialize staking address. Can only be called once. _staking The address of staking contract.
function initialize(address _staking) external { require(_initializer == msg.sender, "DirectBondDepositor: only initializer"); require(_staking != address(0), "DirectBondDepositor: not zero address"); IERC20(ald).safeApprove(_staking, uint256(-1)); staking = _staking; _initializer = address(0); }
13,528,898
/* OwnerController https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Owner controller * * @notice this base contract implements an owner-controller access model. * * @dev the contract is an adapted version of the OpenZeppelin Ownable contract. * It allows the owner to designate an additional account as the controller to * perform restricted operations. * * Other changes include supporting role verification with a require method * in addition to the modifier option, and removing some unneeded functionality. * * Original contract here: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol */ contract OwnerController { address private _owner; address private _controller; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event ControlTransferred( address indexed previousController, address indexed newController ); constructor() { _owner = msg.sender; _controller = msg.sender; emit OwnershipTransferred(address(0), _owner); emit ControlTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current controller. */ function controller() public view returns (address) { return _controller; } /** * @dev Modifier that throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "oc1"); _; } /** * @dev Modifier that throws if called by any account other than the controller. */ modifier onlyController() { require(_controller == msg.sender, "oc2"); _; } /** * @dev Throws if called by any account other than the owner. */ function requireOwner() internal view { require(_owner == msg.sender, "oc1"); } /** * @dev Throws if called by any account other than the controller. */ function requireController() internal view { require(_controller == msg.sender, "oc2"); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). This can * include renouncing ownership by transferring to the zero address. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual { requireOwner(); require(newOwner != address(0), "oc3"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Transfers control of the contract to a new account (`newController`). * Can only be called by the owner. */ function transferControl(address newController) public virtual { requireOwner(); require(newController != address(0), "oc4"); emit ControlTransferred(_controller, newController); _controller = newController; } } /* Pool https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IPool.sol"; import "./interfaces/IPoolFactory.sol"; import "./interfaces/IStakingModule.sol"; import "./interfaces/IRewardModule.sol"; import "./interfaces/IEvents.sol"; import "./OwnerController.sol"; /** * @title Pool * * @notice this implements the GYSR core Pool contract. It supports generalized * incentive mechanisms through a modular architecture, where * staking and reward logic is contained in child contracts. */ contract Pool is IPool, IEvents, ReentrancyGuard, OwnerController { using SafeERC20 for IERC20; // constants uint256 public constant DECIMALS = 18; // modules IStakingModule private immutable _staking; IRewardModule private immutable _reward; // gysr fields IERC20 private immutable _gysr; IPoolFactory private immutable _factory; uint256 private _gysrVested; /** * @param staking_ the staking module address * @param reward_ the reward module address * @param gysr_ address for GYSR token * @param factory_ address for parent factory */ constructor( address staking_, address reward_, address gysr_, address factory_ ) { _staking = IStakingModule(staking_); _reward = IRewardModule(reward_); _gysr = IERC20(gysr_); _factory = IPoolFactory(factory_); } // -- IPool -------------------------------------------------------------- /** * @inheritdoc IPool */ function stakingTokens() external view override returns (address[] memory) { return _staking.tokens(); } /** * @inheritdoc IPool */ function rewardTokens() external view override returns (address[] memory) { return _reward.tokens(); } /** * @inheritdoc IPool */ function stakingBalances(address user) external view override returns (uint256[] memory) { return _staking.balances(user); } /** * @inheritdoc IPool */ function stakingTotals() external view override returns (uint256[] memory) { return _staking.totals(); } /** * @inheritdoc IPool */ function rewardBalances() external view override returns (uint256[] memory) { return _reward.balances(); } /** * @inheritdoc IPool */ function usage() external view override returns (uint256) { return _reward.usage(); } /** * @inheritdoc IPool */ function stakingModule() external view override returns (address) { return address(_staking); } /** * @inheritdoc IPool */ function rewardModule() external view override returns (address) { return address(_reward); } /** * @inheritdoc IPool */ function stake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external override nonReentrant { (address account, uint256 shares) = _staking.stake(msg.sender, amount, stakingdata); (uint256 spent, uint256 vested) = _reward.stake(account, msg.sender, shares, rewarddata); _processGysr(spent, vested); } /** * @inheritdoc IPool */ function unstake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external override nonReentrant { (address account, uint256 shares) = _staking.unstake(msg.sender, amount, stakingdata); (uint256 spent, uint256 vested) = _reward.unstake(account, msg.sender, shares, rewarddata); _processGysr(spent, vested); } /** * @inheritdoc IPool */ function claim( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external override nonReentrant { (address account, uint256 shares) = _staking.claim(msg.sender, amount, stakingdata); (uint256 spent, uint256 vested) = _reward.claim(account, msg.sender, shares, rewarddata); _processGysr(spent, vested); } /** * @inheritdoc IPool */ function update() external override nonReentrant { _staking.update(msg.sender); _reward.update(msg.sender); } /** * @inheritdoc IPool */ function clean() external override nonReentrant { requireController(); _staking.clean(); _reward.clean(); } /** * @inheritdoc IPool */ function gysrBalance() external view override returns (uint256) { return _gysrVested; } /** * @inheritdoc IPool */ function withdraw(uint256 amount) external override { requireController(); require(amount > 0, "p1"); require(amount <= _gysrVested, "p2"); // do transfer _gysr.safeTransfer(msg.sender, amount); _gysrVested = _gysrVested - amount; emit GysrWithdrawn(amount); } /** * @notice transfer control of the Pool and modules to another account * @param newController address of new controller */ function transferControl(address newController) public override { super.transferControl(newController); _staking.transferControl(newController); _reward.transferControl(newController); } // -- Pool internal ----------------------------------------------------- /** * @dev private method to process GYSR spending and vesting * @param spent number of tokens to unstake * @param vested data passed to staking module */ function _processGysr(uint256 spent, uint256 vested) private { // spending if (spent > 0) { _gysr.safeTransferFrom(msg.sender, address(this), spent); } // vesting if (vested > 0) { uint256 fee = (vested * _factory.fee()) / 10**DECIMALS; if (fee > 0) { _gysr.safeTransfer(_factory.treasury(), fee); } _gysrVested = _gysrVested + vested - fee; } } } /* IEvents https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title GYSR event system * * @notice common interface to define GYSR event system */ interface IEvents { // staking event Staked( address indexed user, address indexed token, uint256 amount, uint256 shares ); event Unstaked( address indexed user, address indexed token, uint256 amount, uint256 shares ); event Claimed( address indexed user, address indexed token, uint256 amount, uint256 shares ); // rewards event RewardsDistributed( address indexed user, address indexed token, uint256 amount, uint256 shares ); event RewardsFunded( address indexed token, uint256 amount, uint256 shares, uint256 timestamp ); event RewardsUnlocked(address indexed token, uint256 shares); event RewardsExpired( address indexed token, uint256 amount, uint256 shares, uint256 timestamp ); // gysr event GysrSpent(address indexed user, uint256 amount); event GysrVested(address indexed user, uint256 amount); event GysrWithdrawn(uint256 amount); } /* IPool https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Pool interface * * @notice this defines the core Pool contract interface */ interface IPool { /** * @return staking tokens for Pool */ function stakingTokens() external view returns (address[] memory); /** * @return reward tokens for Pool */ function rewardTokens() external view returns (address[] memory); /** * @return staking balances for user */ function stakingBalances(address user) external view returns (uint256[] memory); /** * @return total staking balances for Pool */ function stakingTotals() external view returns (uint256[] memory); /** * @return reward balances for Pool */ function rewardBalances() external view returns (uint256[] memory); /** * @return GYSR usage ratio for Pool */ function usage() external view returns (uint256); /** * @return address of staking module */ function stakingModule() external view returns (address); /** * @return address of reward module */ function rewardModule() external view returns (address); /** * @notice stake asset and begin earning rewards * @param amount number of tokens to unstake * @param stakingdata data passed to staking module * @param rewarddata data passed to reward module */ function stake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external; /** * @notice unstake asset and claim rewards * @param amount number of tokens to unstake * @param stakingdata data passed to staking module * @param rewarddata data passed to reward module */ function unstake( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external; /** * @notice claim rewards without unstaking * @param amount number of tokens to claim against * @param stakingdata data passed to staking module * @param rewarddata data passed to reward module */ function claim( uint256 amount, bytes calldata stakingdata, bytes calldata rewarddata ) external; /** * @notice method called ad hoc to update user accounting */ function update() external; /** * @notice method called ad hoc to clean up and perform additional accounting */ function clean() external; /** * @return gysr balance available for withdrawal */ function gysrBalance() external view returns (uint256); /** * @notice withdraw GYSR tokens applied during unstaking * @param amount number of GYSR to withdraw */ function withdraw(uint256 amount) external; } /* IPoolFactory https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; /** * @title Pool factory interface * * @notice this defines the Pool factory interface, primarily intended for * the Pool contract to interact with */ interface IPoolFactory { /** * @return GYSR treasury address */ function treasury() external view returns (address); /** * @return GYSR spending fee */ function fee() external view returns (uint256); } /* IRewardModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IEvents.sol"; import "../OwnerController.sol"; /** * @title Reward module interface * * @notice this contract defines the common interface that any reward module * must implement to be compatible with the modular Pool architecture. */ abstract contract IRewardModule is OwnerController, IEvents { // constants uint256 public constant DECIMALS = 18; /** * @return array of reward tokens */ function tokens() external view virtual returns (address[] memory); /** * @return array of reward token balances */ function balances() external view virtual returns (uint256[] memory); /** * @return GYSR usage ratio for reward module */ function usage() external view virtual returns (uint256); /** * @return address of module factory */ function factory() external view virtual returns (address); /** * @notice perform any necessary accounting for new stake * @param account address of staking account * @param user address of user * @param shares number of new shares minted * @param data addtional data * @return amount of gysr spent * @return amount of gysr vested */ function stake( address account, address user, uint256 shares, bytes calldata data ) external virtual returns (uint256, uint256); /** * @notice reward user and perform any necessary accounting for unstake * @param account address of staking account * @param user address of user * @param shares number of shares burned * @param data additional data * @return amount of gysr spent * @return amount of gysr vested */ function unstake( address account, address user, uint256 shares, bytes calldata data ) external virtual returns (uint256, uint256); /** * @notice reward user and perform and necessary accounting for existing stake * @param account address of staking account * @param user address of user * @param shares number of shares being claimed against * @param data addtional data * @return amount of gysr spent * @return amount of gysr vested */ function claim( address account, address user, uint256 shares, bytes calldata data ) external virtual returns (uint256, uint256); /** * @notice method called by anyone to update accounting * @param user address of user for update * @dev will only be called ad hoc and should not contain essential logic */ function update(address user) external virtual; /** * @notice method called by owner to clean up and perform additional accounting * @dev will only be called ad hoc and should not contain any essential logic */ function clean() external virtual; } /* IStakingModule https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IEvents.sol"; import "../OwnerController.sol"; /** * @title Staking module interface * * @notice this contract defines the common interface that any staking module * must implement to be compatible with the modular Pool architecture. */ abstract contract IStakingModule is OwnerController, IEvents { // constants uint256 public constant DECIMALS = 18; /** * @return array of staking tokens */ function tokens() external view virtual returns (address[] memory); /** * @notice get balance of user * @param user address of user * @return balances of each staking token */ function balances(address user) external view virtual returns (uint256[] memory); /** * @return address of module factory */ function factory() external view virtual returns (address); /** * @notice get total staked amount * @return totals for each staking token */ function totals() external view virtual returns (uint256[] memory); /** * @notice stake an amount of tokens for user * @param user address of user * @param amount number of tokens to stake * @param data additional data * @return address of staking account * @return number of shares minted for stake */ function stake( address user, uint256 amount, bytes calldata data ) external virtual returns (address, uint256); /** * @notice unstake an amount of tokens for user * @param user address of user * @param amount number of tokens to unstake * @param data additional data * @return address of staking account * @return number of shares burned for unstake */ function unstake( address user, uint256 amount, bytes calldata data ) external virtual returns (address, uint256); /** * @notice quote the share value for an amount of tokens without unstaking * @param user address of user * @param amount number of tokens to claim with * @param data additional data * @return address of staking account * @return number of shares that the claim amount is worth */ function claim( address user, uint256 amount, bytes calldata data ) external virtual returns (address, uint256); /** * @notice method called by anyone to update accounting * @param user address of user for update * @dev will only be called ad hoc and should not contain essential logic */ function update(address user) external virtual; /** * @notice method called by owner to clean up and perform additional accounting * @dev will only be called ad hoc and should not contain any essential logic */ function clean() external virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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); } } } }
Pool factory interface this defines the Pool factory interface, primarily intended for the Pool contract to interact with/
interface IPoolFactory { function treasury() external view returns (address); function fee() external view returns (uint256); } IPoolFactory }
1,564,285
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /** * @title ScryptFramework * @author Christian Reitwiessner */ abstract contract ScryptFramework { // The state object, can be used in both generating and verifying mode. // In generating mode, only vars and fullMemory is used, in verifying // mode only vars and memoryHash is used. struct State { uint[4] vars; bytes32 memoryHash; // We need the input as part of the state because it is required // for the final step. bytes32 inputHash; // This is not available in verification mode. uint[] fullMemory; } // This is the witness data that is generated in generating mode // and used for verification in verification mode. struct Proofs { bool generateProofs; bool verificationError; bytes32[] proof; } // Only used for testing. /** * @dev hashes a state struct instance * * @param state the state struct instance to hash * * @return returns the hash */ function hashState(State memory state) pure internal returns (bytes32) { return keccak256(abi.encodePacked(state.memoryHash, state.vars, state.inputHash)); } /** * @dev serializes a State struct instance * * @param state the State struct instance to be serialized * * @return encodedState returns the serialized Struct instance */ function encodeState(State memory state) pure internal returns (bytes memory encodedState) { encodedState = abi.encodePacked( state.vars[0], state.vars[1], state.vars[2], state.vars[3], state.memoryHash, state.inputHash ); } /** * @dev de-serializes a State struct instance * * @param encoded the serialized State struct instance * * @return error is true if the input size is wrong * @return state State struct instance */ function decodeState(bytes memory encoded) pure internal returns (bool error, State memory state) { if (encoded.length != 0x20 * 4 + 0x20 + 0x20) { return (true, state); } uint[4] memory vars = state.vars; bytes32 memoryHash; bytes32 inputHash; assembly { mstore(add(vars, 0x00), mload(add(encoded, 0x20))) mstore(add(vars, 0x20), mload(add(encoded, 0x40))) mstore(add(vars, 0x40), mload(add(encoded, 0x60))) mstore(add(vars, 0x60), mload(add(encoded, 0x80))) memoryHash := mload(add(encoded, 0xa0)) inputHash := mload(add(encoded, 0xc0)) } state.memoryHash = memoryHash; state.inputHash = inputHash; return (false, state); } /** * @dev checks for equality of a and b's hash * * @param a the first equality operand * @param b the second equality operand * * @return return true or false */ function equal(bytes memory a, bytes memory b) pure internal returns (bool) { return keccak256(a) == keccak256(b); } /** * @dev populates a State struct instance * * @param input the input that is going to be put inside the State struct instance * * @return state returns a State struct instance */ function inputToState(bytes memory input) pure internal returns (State memory state) { state.inputHash = keccak256(input); state.vars = KeyDeriv.pbkdf2(input, input, 128); state.vars[0] = Salsa8.endianConvert256bit(state.vars[0]); state.vars[1] = Salsa8.endianConvert256bit(state.vars[1]); state.vars[2] = Salsa8.endianConvert256bit(state.vars[2]); state.vars[3] = Salsa8.endianConvert256bit(state.vars[3]); // This is the root hash of empty memory. state.memoryHash = bytes32(0xe82cea94884b1b895ea0742840a3b19249a723810fd1b04d8564d675b0a416f1); initMemory(state); } /** * @dev change the state to the output format * * @param state the final state * * @return output State in output format */ function finalStateToOutput(State memory state, bytes memory input) pure internal returns (bytes memory output) { require(keccak256(input) == state.inputHash); state.vars[0] = Salsa8.endianConvert256bit(state.vars[0]); state.vars[1] = Salsa8.endianConvert256bit(state.vars[1]); state.vars[2] = Salsa8.endianConvert256bit(state.vars[2]); state.vars[3] = Salsa8.endianConvert256bit(state.vars[3]); bytes memory val = uint4ToBytes(state.vars); uint[4] memory values = KeyDeriv.pbkdf2(input, val, 32); require(values[1] == 0 && values[2] == 0 && values[3] == 0); output = new bytes(32); uint val0 = values[0]; assembly { mstore(add(output, 0x20), val0) } } /** * @dev casts a bytes32 array to a bytes array * * @param b the input * * @return r returns the bytes array */ function toBytes(bytes32[] memory b) pure internal returns (bytes memory r) { uint len = b.length * 0x20; r = new bytes(len); assembly { let d := add(r, 0x20) let s := add(b, 0x20) for { let i := 0 } lt(i, len) { i := add(i, 0x20) } { mstore(add(d, i), mload(add(s, i))) } } } /** * @dev casts a bytes array into a bytes32 array * * @param b the input bytes array * * @return error Returns whether the input length module 0x20 is 0 * @return r The bytes32 array */ function toArray(bytes memory b) pure internal returns (bool error, bytes32[] memory r) { if (b.length % 0x20 != 0) { return (true, r); } uint len = b.length; r = new bytes32[](b.length / 0x20); assembly { let d := add(r, 0x20) let s := add(b, 0x20) for { let i := 0 } lt(i, len) { i := add(i, 0x20) } { mstore(add(d, i), mload(add(s, i))) } } } /** * @dev convert a 4-member array into a byte stream * * @param val the input array that has 4 members * * @return r the byte stream */ function uint4ToBytes(uint[4] memory val) pure internal returns (bytes memory r) { r = new bytes(4 * 32); uint v = val[0]; assembly { mstore(add(r, 0x20), v) } v = val[1]; assembly { mstore(add(r, 0x40), v) } v = val[2]; assembly { mstore(add(r, 0x60), v) } v = val[3]; assembly { mstore(add(r, 0x80), v) } } // Virtual functions to be implemented in either the runner/prover or the verifier. function initMemory(State memory state) pure virtual internal; function writeMemory(State memory state, uint index, uint[4] memory values, Proofs memory proofs) pure virtual internal; function readMemory(State memory state, uint index, Proofs memory proofs) pure virtual internal returns (uint, uint, uint, uint); /** * @dev runs a single step, modifying the state. * This in turn calls the virtual functions readMemory and writeMemory. * * @param state the state structure * @param step which step to run * @param proofs the proofs structure */ function runStep(State memory state, uint step, Proofs memory proofs) pure internal { require(step < 2048); if (step < 1024) { writeMemory(state, step, state.vars, proofs); state.vars = Salsa8.round(state.vars); } else { uint readIndex = (state.vars[2] / 0x100000000000000000000000000000000000000000000000000000000) % 1024; (uint va, uint vb, uint vc, uint vd) = readMemory(state, readIndex, proofs); state.vars = Salsa8.round([ state.vars[0] ^ va, state.vars[1] ^ vb, state.vars[2] ^ vc, state.vars[3] ^ vd ]); } } } library Salsa8 { uint constant m0 = 0x100000000000000000000000000000000000000000000000000000000; uint constant m1 = 0x1000000000000000000000000000000000000000000000000; uint constant m2 = 0x010000000000000000000000000000000000000000; uint constant m3 = 0x100000000000000000000000000000000; uint constant m4 = 0x1000000000000000000000000; uint constant m5 = 0x10000000000000000; uint constant m6 = 0x100000000; uint constant m7 = 0x1; /** * @dev calculates a quarter of a slasa round on a row/column of the matrix * * @param y0 the first element * @param y1 the second element * @param y2 the third element * @param y3 the fourth element * * @return the updated elements after a quarter of a salsa round on a row/column of the matrix */ function quarter(uint32 y0, uint32 y1, uint32 y2, uint32 y3) pure internal returns (uint32, uint32, uint32, uint32) { uint32 t; t = y0 + y3; y1 = y1 ^ ((t * 2**7) | (t / 2**(32-7))); t = y1 + y0; y2 = y2 ^ ((t * 2**9) | (t / 2**(32-9))); t = y2 + y1; y3 = y3 ^ ((t * 2**13) | (t / 2**(32-13))); t = y3 + y2; y0 = y0 ^ ((t * 2**18) | (t / 2**(32-18))); return (y0, y1, y2, y3); } /** * @dev extracts a 32-bit word from the uint256 word. * * @param data the uint256 word from where we would like to extract a 32-bit word. * @param word which 32-bit word to extract, 0 denotes the most signifacant 32-bit word. * * @return x The 32-bit extracted word */ function get(uint data, uint word) pure internal returns (uint32 x) { return uint32(data / 2**(256 - word * 32 - 32)); } /** * @dev shifts a 32-bit value inside a uint256 for a set amount of 32-bit words to the left * * @param x the 32-bit value to shift. * @param word how many 32-bit words to shift x to the lefy by. * * @return A uint256 value containing x shifted to the left by word*32. */ function put(uint x, uint word) pure internal returns (uint) { return x * 2**(256 - word * 32 - 32); } /** * @dev calculates a slasa transposed rounds by doing the round on the rows. * * @param first a uint256 value containing the first half of the salsa matrix i.e. the first 8 elements. * @param second a uint256 value containing the second half of the salsa matrix i.e. the second 8 elements. * * @return f The updated first half of the salsa matrix. * @return s The updated second half of the salsa matrix. */ function rowround(uint first, uint second) pure internal returns (uint f, uint s) { (uint32 a, uint32 b, uint32 c, uint32 d) = quarter(uint32(first / m0), uint32(first / m1), uint32(first / m2), uint32(first / m3)); f = (((((uint(a) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d); (b,c,d,a) = quarter(uint32(first / m5), uint32(first / m6), uint32(first / m7), uint32(first / m4)); f = (((((((f * 2**32) | uint(a)) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d); (c,d,a,b) = quarter(uint32(second / m2), uint32(second / m3), uint32(second / m0), uint32(second / m1)); s = (((((uint(a) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d); (d,a,b,c) = quarter(uint32(second / m7), uint32(second / m4), uint32(second / m5), uint32(second / m6)); s = (((((((s * 2**32) | uint(a)) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d); } /** * @dev calculates a salsa column round. * * @param first a uint256 value containing the first half of the salsa matrix. * @param second a uint256 value containing the second half of the salsa matrix. * * @return f The first half of the salsa matrix. * @return s The second half of the salsa matrix. */ function columnround(uint first, uint second) pure internal returns (uint f, uint s) { (uint32 a, uint32 b, uint32 c, uint32 d) = quarter(uint32(first / m0), uint32(first / m4), uint32(second / m0), uint32(second / m4)); f = (uint(a) * m0) | (uint(b) * m4); s = (uint(c) * m0) | (uint(d) * m4); (a,b,c,d) = quarter(uint32(first / m5), uint32(second / m1), uint32(second / m5), uint32(first / m1)); f |= (uint(a) * m5) | (uint(d) * m1); s |= (uint(b) * m1) | (uint(c) * m5); (a,b,c,d) = quarter(uint32(second / m2), uint32(second / m6), uint32(first / m2), uint32(first / m6)); f |= (uint(c) * m2) | (uint(d) * m6); s |= (uint(a) * m2) | (uint(b) * m6); (a,b,c,d) = quarter(uint32(second / m7), uint32(first / m3), uint32(first / m7), uint32(second / m3)); f |= (uint(b) * m3) | (uint(c) * m7); s |= (uint(a) * m7) | (uint(d) * m3); } /** * @dev run salsa20_8 on the input matrix * * @param _first the first half of the input matrix to salsa. * @param _second the sesond half of the input matrix to salsa. * * @return rfirst The first half of the resulting salsa matrix. * @return rsecond The second half of the resulting salsa matrix. */ function salsa20_8(uint _first, uint _second) pure internal returns (uint rfirst, uint rsecond) { uint first = _first; uint second = _second; for (uint i = 0; i < 8; i += 2) { (first, second) = columnround(first, second); (first, second) = rowround(first, second); } for (uint i = 0; i < 8; i++) { rfirst |= put(get(_first, i) + get(first, i), i); rsecond |= put(get(_second, i) + get(second, i), i); } } /** * @dev flips the endianness of a 256-bit value * * @param x the input * * @return the flipped value */ function endianConvert256bit(uint x) pure internal returns (uint) { return endianConvert32bit(x / m0) * m0 + endianConvert32bit(x / m1) * m1 + endianConvert32bit(x / m2) * m2 + endianConvert32bit(x / m3) * m3 + endianConvert32bit(x / m4) * m4 + endianConvert32bit(x / m5) * m5 + endianConvert32bit(x / m6) * m6 + endianConvert32bit(x / m7) * m7; } /** * @dev flips endianness for a 32-bit input * * @param x the 32-bit value to have its endianness flipped * * @return the flipped value */ function endianConvert32bit(uint x) pure internal returns (uint) { return (x & 0xff) * 0x1000000 + (x & 0xff00) * 0x100 + (x & 0xff0000) / 0x100 + (x & 0xff000000) / 0x1000000; } /** * @dev runs Salsa8 on input values * * @param values the input values for Salsa8 * * @return returns the result of running Salsa8 on the input values */ function round(uint[4] memory values) pure internal returns (uint[4] memory) { (uint a, uint b, uint c, uint d) = (values[0], values[1], values[2], values[3]); (a, b) = salsa20_8(a ^ c, b ^ d); (c, d) = salsa20_8(a ^ c, b ^ d); return [a, b, c, d]; } } library KeyDeriv { /** * @dev hmacsha256 * * @param key the key * @param message the message to hash * * @return the hash result */ function hmacsha256(bytes memory key, bytes memory message) pure internal returns (bytes32) { bytes32 keyl; bytes32 keyr; if (key.length > 64) { keyl = sha256(key); } else { for (uint i = 0; i < key.length && i < 32; i++) keyl |= bytes32(key[i]) >> (8 * i); for (uint i = 32; i < key.length && i < 64; i++) keyr |= bytes32(key[i]) >> (8 * (i - 32)); } bytes32 threesix = 0x3636363636363636363636363636363636363636363636363636363636363636; bytes32 fivec = 0x5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c; return sha256(abi.encodePacked(fivec ^ keyl, fivec ^ keyr, sha256(abi.encodePacked(threesix ^ keyl, threesix ^ keyr, message)))); } /// PBKDF2 restricted to c=1, hash = hmacsha256 and dklen being a multiple of 32 not larger than 128 /** * @dev pbkdf2 * * @param key the password * @param salt cryptographic salt * @param dklen desired length of the key * * @return r The generated key */ function pbkdf2(bytes memory key, bytes memory salt, uint dklen) pure internal returns (uint[4] memory r) { bytes memory message = new bytes(salt.length + 4); for (uint i = 0; i < salt.length; i++) { message[i] = salt[i]; } for (uint i = 0; i * 32 < dklen; i++) { message[message.length - 1] = bytes1(uint8(i + 1)); r[i] = uint(hmacsha256(key, message)); } } }
de-serializes a State struct instance encoded the serialized State struct instance return error is true if the input size is wrong return state State struct instance/
function decodeState(bytes memory encoded) pure internal returns (bool error, State memory state) { if (encoded.length != 0x20 * 4 + 0x20 + 0x20) { return (true, state); } uint[4] memory vars = state.vars; bytes32 memoryHash; bytes32 inputHash; assembly { mstore(add(vars, 0x00), mload(add(encoded, 0x20))) mstore(add(vars, 0x20), mload(add(encoded, 0x40))) mstore(add(vars, 0x40), mload(add(encoded, 0x60))) mstore(add(vars, 0x60), mload(add(encoded, 0x80))) memoryHash := mload(add(encoded, 0xa0)) inputHash := mload(add(encoded, 0xc0)) } state.memoryHash = memoryHash; state.inputHash = inputHash; return (false, state); }
15,824,387
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "./ERC998TopDown.sol"; import "./ILootmart.sol"; interface IRegistry { function isValid721Contract(address _contract) external view returns (bool); function isValid1155Contract(address _contract) external view returns (bool); function isValidContract(address _contract) external view returns (bool); function isValidItemType(string memory _itemType) external view returns (bool); } /// @title Adventurer /// @author Gary Thung /// @notice Adventurer is a composable NFT designed to equip other ERC721 and ERC1155 tokens contract Adventurer is ERC721Enumerable, ERC998TopDown, Ownable { using ERC165Checker for address; struct Item { address itemAddress; uint256 id; } event Equipped(uint256 indexed tokenId, address indexed itemAddress, uint256 indexed itemId, string itemType); event Unequipped(uint256 indexed tokenId, address indexed itemAddress, uint256 indexed itemId, string itemType); mapping(uint256 => mapping(string => Item)) public equipped; bytes4 internal constant ERC_721_INTERFACE = 0x80ac58cd; bytes4 internal constant ERC_1155_INTERFACE = 0xd9b67a26; IRegistry internal registry; constructor(address _registry) ERC998TopDown("Adventurer", "ADVT") { registry = IRegistry(_registry); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, ERC721) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Ensure caller affecting an adventurer is authorized. */ modifier onlyAuthorized(uint256 _tokenId) { require(_isApprovedOrOwner(msg.sender, _tokenId), "Adventurer: Caller is not owner nor approved"); _; } // MINTING // function mint() external { _safeMint(_msgSender(), totalSupply()); } function mintToAccount(address _account) external { _safeMint(_account, totalSupply()); } // EQUIPPING/UNEQUIPPING // /** * @dev Execute a series of equips followed by a series of unequips. * * NOTE: Clients should reduce the changes down to the simplest set. * For example, imagine an Adventurer with a head equipped and the goal is to equip a new head item. * Calling bulkChanges with both a new head to equip and a head unequip will result in the Adventurer * ultimately having no head equipped. The simplest change would be to do only an equip. */ function bulkChanges( uint256 _tokenId, address[] memory _equipItemAddresses, uint256[] memory _equipItemIds, string[] memory _unequipItemTypes ) external onlyAuthorized(_tokenId) { // Execute equips for (uint256 i = 0; i < _equipItemAddresses.length; i++) { _equip(_tokenId, _equipItemAddresses[i], _equipItemIds[i]); } // Execute unequips for (uint256 i = 0; i < _unequipItemTypes.length; i++) { _unequip(_tokenId, _unequipItemTypes[i]); } } /** * @dev Equip an item. */ function equip( uint256 _tokenId, address _itemAddress, uint256 _itemId ) external onlyAuthorized(_tokenId) { _equip(_tokenId, _itemAddress, _itemId); } /** * @dev Equip a list of items. */ function equipBulk( uint256 _tokenId, address[] memory _itemAddresses, uint256[] memory _itemIds ) external onlyAuthorized(_tokenId) { for (uint256 i = 0; i < _itemAddresses.length; i++) { _equip(_tokenId, _itemAddresses[i], _itemIds[i]); } } /** * @dev Unequip an item. */ function unequip( uint256 _tokenId, string memory _itemType ) external onlyAuthorized(_tokenId) { _unequip(_tokenId, _itemType); } /** * @dev Unequip a list of items. */ function unequipBulk( uint256 _tokenId, string[] memory _itemTypes ) external onlyAuthorized(_tokenId) { for (uint256 i = 0; i < _itemTypes.length; i++) { _unequip(_tokenId, _itemTypes[i]); } } // LOGIC // /** * @dev Execute inbound transfer from a component contract to this contract. */ function _transferItemIn( uint256 _tokenId, address _operator, address _itemAddress, uint256 _itemId ) internal { if (_itemAddress.supportsInterface(ERC_721_INTERFACE)) { IERC721(_itemAddress).safeTransferFrom(_operator, address(this), _itemId, toBytes(_tokenId)); } else if (_itemAddress.supportsInterface(ERC_1155_INTERFACE)) { IERC1155(_itemAddress).safeTransferFrom(_operator, address(this), _itemId, 1, toBytes(_tokenId)); } else { require(false, "Adventurer: Item does not support ERC-721 nor ERC-1155 standards"); } } /** * @dev Execute outbound transfer of a child token. */ function _transferItemOut( uint256 _tokenId, address _owner, address _itemAddress, uint256 _itemId ) internal { if (child721Balance(_tokenId, _itemAddress, _itemId) == 1) { safeTransferChild721From(_tokenId, _owner, _itemAddress, _itemId, ""); } else if (child1155Balance(_tokenId, _itemAddress, _itemId) >= 1) { safeTransferChild1155From(_tokenId, _owner, _itemAddress, _itemId, 1, ""); } } /** * @dev Execute the logic required to equip a single item. This involves: * * 1. Checking that the component contract is registered * 2. Check that the item type is valid * 3. Mark the new item as equipped * 4. Transfer the new item to this contract * 5. Transfer the old item back to the owner */ function _equip( uint256 _tokenId, address _itemAddress, uint256 _itemId ) internal { require(registry.isValidContract(_itemAddress), "Adventurer: Item contract must be in the registry"); string memory itemType = ILootmart(_itemAddress).itemTypeFor(_itemId); require(registry.isValidItemType(itemType), "Adventurer: Invalid item type"); // Get current item Item memory item = equipped[_tokenId][itemType]; address currentItemAddress = item.itemAddress; uint256 currentItemId = item.id; // Equip the new item equipped[_tokenId][itemType] = Item({ itemAddress: _itemAddress, id: _itemId }); // Pull in the item _transferItemIn(_tokenId, _msgSender(), _itemAddress, _itemId); // Send back old item if (currentItemAddress != address(0)) { _transferItemOut(_tokenId, ownerOf(_tokenId), currentItemAddress, currentItemId); } emit Equipped(_tokenId, _itemAddress, _itemId, itemType); } /** * @dev Execute the logic required to equip a single item. This involves: * * 1. Mark the item as unequipped * 2. Transfer the item back to the owner */ function _unequip( uint256 _tokenId, string memory _itemType ) internal { // Get current item Item memory item = equipped[_tokenId][_itemType]; address currentItemAddress = item.itemAddress; uint256 currentItemId = item.id; // Mark item unequipped delete equipped[_tokenId][_itemType]; // Send back old item _transferItemOut(_tokenId, ownerOf(_tokenId), currentItemAddress, currentItemId); emit Unequipped(_tokenId, currentItemAddress, currentItemId, _itemType); } // CALLBACKS // /** * @dev Only allow this contract to execute inbound transfers. Executes super's receiver to update underlying bookkeeping. */ function onERC721Received( address operator, address from, uint256 id, bytes memory data ) public override returns (bytes4) { require(operator == address(this), "Adventurer: Only the Adventurer contract can pull items in"); return super.onERC721Received(operator, from, id, data); } /** * @dev Only allow this contract to execute inbound transfers. Executes super's receiver to update underlying bookkeeping. */ function onERC1155Received( address operator, address from, uint256 id, uint256 amount, bytes memory data ) public override returns (bytes4) { require(operator == address(this), "Only the Adventurer contract can pull items in"); return super.onERC1155Received(operator, from, id, amount, data); } /** * @dev Only allow this contract to execute inbound transfers. Executes super's receiver to update underlying bookkeeping. */ function onERC1155BatchReceived( address operator, address from, uint256[] memory ids, uint256[] memory values, bytes memory data ) public override returns (bytes4) { require(operator == address(this), "Only the Adventurer contract can pull items in"); return super.onERC1155BatchReceived(operator, from, ids, values, data); } function _beforeChild721Transfer( address operator, uint256 fromTokenId, address to, address childContract, uint256 id, bytes memory data ) internal override virtual { super._beforeChild721Transfer(operator, fromTokenId, to, childContract, id, data); } function _beforeChild1155Transfer( address operator, uint256 fromTokenId, address to, address childContract, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override virtual { super._beforeChild1155Transfer(operator, fromTokenId, to, childContract, ids, amounts, data); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } // HELPERS // /** * @dev Convert uint to bytes. */ function toBytes(uint256 x) internal pure returns (bytes memory b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; 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 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 "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "./IERC998ERC721TopDown.sol"; import "./IERC998ERC1155TopDown.sol"; contract ERC998TopDown is ERC721, IERC998ERC721TopDown, IERC998ERC1155TopDown { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; // What tokens does the 998 own, by child address? // _balances[tokenId][child address] = [child tokenId 1, child tokenId 2] mapping(uint256 => mapping(address => EnumerableSet.UintSet)) internal _balances721; // Which 998s own a a child 721 contract's token? // _holdersOf[child address] = [tokenId 1, tokenId 2] mapping(address => EnumerableSet.UintSet) internal _holdersOf721; // _balances[tokenId][child address][child tokenId] = amount mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal _balances1155; // _holdersOf[child address][child tokenId] = [tokenId 1, tokenId 2] mapping(address => mapping(uint256 => EnumerableSet.UintSet)) internal _holdersOf1155; // What child 721 contracts does a token have children of? // _child721Contracts[tokenId] = [child address 1, child address 2] mapping(uint256 => EnumerableSet.AddressSet) internal _child721Contracts; // What child tokens does a token have for a child 721 contract? // _childrenForChild721Contracts[tokenId][child address] = [child tokenId 1, child tokenId 2] mapping(uint256 => mapping(address => EnumerableSet.UintSet)) internal _childrenForChild721Contracts; mapping(uint256 => EnumerableSet.AddressSet) internal _child1155Contracts; mapping(uint256 => mapping(address => EnumerableSet.UintSet)) internal _childrenForChild1155Contracts; constructor(string memory name, string memory symbol) ERC721(name, symbol) {} /** * @dev Gives child balance for a specific child 721 contract. */ function child721Balance(uint256 tokenId, address childContract, uint256 childTokenId) public view override returns (uint256) { return _balances721[tokenId][childContract].contains(childTokenId) ? 1 : 0; } /** * @dev Gives child balance for a specific child 1155 contract and child id. */ function child1155Balance(uint256 tokenId, address childContract, uint256 childTokenId) public view override returns (uint256) { return _balances1155[tokenId][childContract][childTokenId]; } /** * @dev Gives list of child 721 contracts where token ID has childs. */ function child721ContractsFor(uint256 tokenId) override public view returns (address[] memory) { address[] memory childContracts = new address[](_child721Contracts[tokenId].length()); for(uint256 i = 0; i < _child721Contracts[tokenId].length(); i++) { childContracts[i] = _child721Contracts[tokenId].at(i); } return childContracts; } /** * @dev Gives list of child 1155 contracts where token ID has childs. */ function child1155ContractsFor(uint256 tokenId) override public view returns (address[] memory) { address[] memory childContracts = new address[](_child1155Contracts[tokenId].length()); for(uint256 i = 0; i < _child1155Contracts[tokenId].length(); i++) { childContracts[i] = _child1155Contracts[tokenId].at(i); } return childContracts; } /** * @dev Gives list of owned child IDs on a child 721 contract by token ID. */ function child721IdsForOn(uint256 tokenId, address childContract) override public view returns (uint256[] memory) { uint256[] memory childTokenIds = new uint256[](_childrenForChild721Contracts[tokenId][childContract].length()); for(uint256 i = 0; i < _childrenForChild721Contracts[tokenId][childContract].length(); i++) { childTokenIds[i] = _childrenForChild721Contracts[tokenId][childContract].at(i); } return childTokenIds; } /** * @dev Gives list of owned child IDs on a child 1155 contract by token ID. */ function child1155IdsForOn(uint256 tokenId, address childContract) override public view returns (uint256[] memory) { uint256[] memory childTokenIds = new uint256[](_childrenForChild1155Contracts[tokenId][childContract].length()); for(uint256 i = 0; i < _childrenForChild1155Contracts[tokenId][childContract].length(); i++) { childTokenIds[i] = _childrenForChild1155Contracts[tokenId][childContract].at(i); } return childTokenIds; } /** * @dev Transfers child 721 token from a token ID. */ function safeTransferChild721From(uint256 fromTokenId, address to, address childContract, uint256 childTokenId, bytes memory data) public override { require(to != address(0), "ERC998: transfer to the zero address"); address operator = _msgSender(); require( ownerOf(fromTokenId) == operator || isApprovedForAll(ownerOf(fromTokenId), operator), "ERC998: caller is not owner nor approved" ); _beforeChild721Transfer(operator, fromTokenId, to, childContract, childTokenId, data); _removeChild721(fromTokenId, childContract, childTokenId); ERC721(childContract).safeTransferFrom(address(this), to, childTokenId, data); emit TransferChild721(fromTokenId, to, childContract, childTokenId); } /** * @dev Transfers child 1155 token from a token ID. */ function safeTransferChild1155From(uint256 fromTokenId, address to, address childContract, uint256 childTokenId, uint256 amount, bytes memory data) public override { require(to != address(0), "ERC998: transfer to the zero address"); address operator = _msgSender(); require( ownerOf(fromTokenId) == operator || isApprovedForAll(ownerOf(fromTokenId), operator), "ERC998: caller is not owner nor approved" ); _beforeChild1155Transfer(operator, fromTokenId, to, childContract, _asSingletonArray(childTokenId), _asSingletonArray(amount), data); _removeChild1155(fromTokenId, childContract, childTokenId, amount); ERC1155(childContract).safeTransferFrom(address(this), to, childTokenId, amount, data); emit TransferSingleChild1155(fromTokenId, to, childContract, childTokenId, amount); } /** * @dev Transfers batch of child 1155 tokens from a token ID. */ function safeBatchTransferChild1155From(uint256 fromTokenId, address to, address childContract, uint256[] memory childTokenIds, uint256[] memory amounts, bytes memory data) public override { require(childTokenIds.length == amounts.length, "ERC998: ids and amounts length mismatch"); require(to != address(0), "ERC998: transfer to the zero address"); address operator = _msgSender(); require( ownerOf(fromTokenId) == operator || isApprovedForAll(ownerOf(fromTokenId), operator), "ERC998: caller is not owner nor approved" ); _beforeChild1155Transfer(operator, fromTokenId, to, childContract, childTokenIds, amounts, data); for (uint256 i = 0; i < childTokenIds.length; ++i) { uint256 childTokenId = childTokenIds[i]; uint256 amount = amounts[i]; _removeChild1155(fromTokenId, childContract, childTokenId, amount); } ERC1155(childContract).safeBatchTransferFrom(address(this), to, childTokenIds, amounts, data); emit TransferBatchChild1155(fromTokenId, to, childContract, childTokenIds, amounts); } /** * @dev Receives a child token, the receiver token ID must be encoded in the * field data. Operator is the account who initiated the transfer. */ function onERC721Received(address operator, address from, uint256 id, bytes memory data) virtual public override returns (bytes4) { require(data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to"); uint256 _receiverTokenId; uint256 _index = msg.data.length - 32; assembly {_receiverTokenId := calldataload(_index)} _receiveChild721(_receiverTokenId, msg.sender, id); emit ReceivedChild721(from, _receiverTokenId, msg.sender, id); return this.onERC721Received.selector; } /** * @dev Receives a child token, the receiver token ID must be encoded in the * field data. Operator is the account who initiated the transfer. */ function onERC1155Received(address operator, address from, uint256 id, uint256 amount, bytes memory data) virtual public override returns (bytes4) { require(data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to"); uint256 _receiverTokenId; uint256 _index = msg.data.length - 32; assembly {_receiverTokenId := calldataload(_index)} _receiveChild1155(_receiverTokenId, msg.sender, id, amount); emit ReceivedChild1155(from, _receiverTokenId, msg.sender, id, amount); return this.onERC1155Received.selector; } /** * @dev Receives a batch of child tokens, the receiver token ID must be * encoded in the field data. Operator is the account who initiated the transfer. */ function onERC1155BatchReceived(address operator, address from, uint256[] memory ids, uint256[] memory values, bytes memory data) virtual public override returns (bytes4) { require(data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to"); require(ids.length == values.length, "ERC1155: ids and values length mismatch"); uint256 _receiverTokenId; uint256 _index = msg.data.length - 32; assembly {_receiverTokenId := calldataload(_index)} for (uint256 i = 0; i < ids.length; i++) { _receiveChild1155(_receiverTokenId, msg.sender, ids[i], values[i]); emit ReceivedChild1155(from, _receiverTokenId, msg.sender, ids[i], values[i]); } return this.onERC1155BatchReceived.selector; } /** * @dev Update bookkeeping when a 998 is sent a child 721 token. */ function _receiveChild721(uint256 tokenId, address childContract, uint256 childTokenId) internal virtual { if (!_child721Contracts[tokenId].contains(childContract)) { _child721Contracts[tokenId].add(childContract); } if (!_balances721[tokenId][childContract].contains(childTokenId)) { _childrenForChild721Contracts[tokenId][childContract].add(childTokenId); } _balances721[tokenId][childContract].add(childTokenId); } /** * @dev Update bookkeeping when a child 721 token is removed from a 998. */ function _removeChild721(uint256 tokenId, address childContract, uint256 childTokenId) internal virtual { require(_balances721[tokenId][childContract].contains(childTokenId), "ERC998: insufficient child balance for transfer"); _balances721[tokenId][childContract].remove(childTokenId); _holdersOf721[childContract].remove(tokenId); _childrenForChild721Contracts[tokenId][childContract].remove(childTokenId); if (_childrenForChild721Contracts[tokenId][childContract].length() == 0) { _child721Contracts[tokenId].remove(childContract); } } /** * @dev Update bookkeeping when a 998 is sent a child 1155 token. */ function _receiveChild1155(uint256 tokenId, address childContract, uint256 childTokenId, uint256 amount) internal virtual { if (!_child1155Contracts[tokenId].contains(childContract)) { _child1155Contracts[tokenId].add(childContract); } if (_balances1155[tokenId][childContract][childTokenId] == 0) { _childrenForChild1155Contracts[tokenId][childContract].add(childTokenId); } _balances1155[tokenId][childContract][childTokenId] += amount; } /** * @dev Update bookkeeping when a child 1155 token is removed from a 998. */ function _removeChild1155(uint256 tokenId, address childContract, uint256 childTokenId, uint256 amount) internal virtual { require(amount != 0 || _balances1155[tokenId][childContract][childTokenId] >= amount, "ERC998: insufficient child balance for transfer"); _balances1155[tokenId][childContract][childTokenId] -= amount; if (_balances1155[tokenId][childContract][childTokenId] == 0) { _holdersOf1155[childContract][childTokenId].remove(tokenId); _childrenForChild1155Contracts[tokenId][childContract].remove(childTokenId); if (_childrenForChild1155Contracts[tokenId][childContract].length() == 0) { _child1155Contracts[tokenId].remove(childContract); } } } function _beforeChild721Transfer( address operator, uint256 fromTokenId, address to, address childContract, uint256 id, bytes memory data ) internal virtual { } function _beforeChild1155Transfer( address operator, uint256 fromTokenId, address to, address childContract, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; // Any component stores need to have this function so that Adventurer can determine what // type of item it is interface ILootmart { function itemTypeFor(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT 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)) internal _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 { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( 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 `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (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 `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.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 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 pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; interface IERC998ERC721TopDown is IERC721, IERC721Receiver { event ReceivedChild721(address indexed from, uint256 indexed toTokenId, address indexed childContract, uint256 childTokenId); event TransferChild721(uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256 childTokenId); function child721ContractsFor(uint256 tokenId) external view returns (address[] memory childContracts); function child721IdsForOn(uint256 tokenId, address childContract) external view returns (uint256[] memory childIds); function child721Balance(uint256 tokenId, address childContract, uint256 childTokenId) external view returns(uint256); function safeTransferChild721From(uint256 fromTokenId, address to, address childContract, uint256 childTokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; interface IERC998ERC1155TopDown is IERC721, IERC1155Receiver { event ReceivedChild1155(address indexed from, uint256 indexed toTokenId, address indexed childContract, uint256 childTokenId, uint256 amount); event TransferSingleChild1155(uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256 childTokenId, uint256 amount); event TransferBatchChild1155(uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256[] childTokenIds, uint256[] amounts); function child1155ContractsFor(uint256 tokenId) external view returns (address[] memory childContracts); function child1155IdsForOn(uint256 tokenId, address childContract) external view returns (uint256[] memory childIds); function child1155Balance(uint256 tokenId, address childContract, uint256 childTokenId) external view returns(uint256); function safeTransferChild1155From(uint256 fromTokenId, address to, address childContract, uint256 childTokenId, uint256 amount, bytes calldata data) external; function safeBatchTransferChild1155From(uint256 fromTokenId, address to, address childContract, uint256[] calldata childTokenIds, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT 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); }
Transfers child 1155 token from a token ID./
function safeTransferChild1155From(uint256 fromTokenId, address to, address childContract, uint256 childTokenId, uint256 amount, bytes memory data) public override { require(to != address(0), "ERC998: transfer to the zero address"); address operator = _msgSender(); require( ownerOf(fromTokenId) == operator || isApprovedForAll(ownerOf(fromTokenId), operator), "ERC998: caller is not owner nor approved" ); _beforeChild1155Transfer(operator, fromTokenId, to, childContract, _asSingletonArray(childTokenId), _asSingletonArray(amount), data); _removeChild1155(fromTokenId, childContract, childTokenId, amount); ERC1155(childContract).safeTransferFrom(address(this), to, childTokenId, amount, data); emit TransferSingleChild1155(fromTokenId, to, childContract, childTokenId, amount); }
1,739,589
// Copyright © 2021 Treum.io, a ConsenSys AG company. All rights reserved. // BY USING THIS SMART CONTRACT, INCLUDING TO BUY, SELL, CREATE, BURN OR USE TOKENS, YOU AGREE TO EULERBEATS’ TERMS OF SERVICE, AVAILABLE HERE: HTTPS://EULERBEATS.COM/TERMS-OF-SERVICE AND IN THE TRANSACTION DATA OF 0x56ff8befa16e6720f9cf54146c9c5e3be9a1258fd910fe55c287f19ad80b8bc1 // SHA256 of artwork generation script: 65301d8425ba637bdb6328a17dbe7440bf1c7f5032879aad4c00bfa09bddf93f pragma solidity =0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./RoyaltyDistributor.sol"; // EulerBeats are generative visual & audio art pieces. The recipe and instructions to re-create the visualization and music reside on Ethereum blockchain. // // To recreate your art, you will need to retrieve the script // // STEPS TO RETRIEVE THE SCRIPTS: // - The artwork re-generation script is written in JavaScript, split into pieces, and stored on chain. // - Query the contract for the scriptCount - this is the number of pieces of the re-genereation script. You will need all of them. // - Run the getScriptAtIndex method in the EulerBeats smart contract starting with parameter 0, this is will return a transaction hash // - The "Input Data" field of this transaction contains the first segment of the script. Convert this into UTF-8 format // - Repeat these last two steps, incrementing the parameter in the getScriptAtIndex method until the number of script segments matches the scrtipCount contract EulerBeatsV2 is Ownable, ERC1155, ReentrancyGuard, RoyaltyDistributor { using SafeMath for uint256; using Strings for uint256; using Address for address payable; /***********************************| | Variables and Events | |__________________________________*/ // For Mint, mintPrint, and burnPrint: locks the prices bool public mintPrintEnabled = false; bool public burnPrintEnabled = false; bool public mintEnabled = false; bool private _contractMintPrintEnabled = false; // For metadata (scripts), when locked it is irreversible bool private _locked = false; // Number of script sections stored uint256 public scriptCount = 0; // The scripts that can be used to render the NFT (audio and visual) mapping (uint256 => string) public scripts; // The bit flag to distinguish prints uint256 constant public PRINTS_FLAG_BIT = 1; // Supply restriction on prints uint256 constant public MAX_PRINT_SUPPLY = 160; // Supply restriction on seeds/original NFTs uint256 constant public MAX_SEEDS_SUPPLY = 27; // Total supply of prints and original NFTs mapping(uint256 => uint256) public totalSupply; // Total number of original NFTs minted uint256 public originalsMinted = 0; // Funds reserved for burns uint256 public reserve = 0; // Contract name string public name; // Contract symbol string public symbol; // Constants for bonding curve pricing uint256 constant public A = 12; uint256 constant public B = 140; uint256 constant public C = 100; uint256 constant public SIG_DIGITS = 3; // Base uri for overriding ERC1155's uri getter string internal _baseURI; /** * @dev Emitted when an original NFT with a new seed is minted */ event MintOriginal(address indexed to, uint256 seed, uint256 indexed originalsMinted); /** * @dev Emitted when an print is minted */ event PrintMinted( address indexed to, uint256 id, uint256 indexed seed, uint256 pricePaid, uint256 nextPrintPrice, uint256 nextBurnPrice, uint256 printsSupply, uint256 royaltyPaid, uint256 reserve, address indexed royaltyRecipient ); /** * @dev Emitted when an print is burned */ event PrintBurned( address indexed to, uint256 id, uint256 indexed seed, uint256 priceReceived, uint256 nextPrintPrice, uint256 nextBurnPrice, uint256 printsSupply, uint256 reserve ); constructor(string memory _name, string memory _symbol, string memory _uri) ERC1155("") { name = _name; symbol = _symbol; _baseURI = _uri; } /***********************************| | Modifiers | |__________________________________*/ modifier onlyWhenMintEnabled() { require(mintEnabled, "Minting originals is disabled"); _; } modifier onlyWhenMintPrintEnabled() { require(mintPrintEnabled, "Minting prints is disabled"); _; } modifier onlyWhenBurnPrintEnabled() { require(burnPrintEnabled, "Burning prints is disabled"); _; } modifier onlyUnlocked() { require(!_locked, "Contract is locked"); _; } /***********************************| | User Interactions | |__________________________________*/ /** * @dev Function to mint tokens. Not payable for V2, restricted to owner */ function mint() external onlyOwner onlyWhenMintEnabled returns (uint256) { uint256 newOriginalsSupply = originalsMinted.add(1); require( newOriginalsSupply <= MAX_SEEDS_SUPPLY, "Max supply reached" ); // The generated seed == the original nft token id. // Both terms are used throughout and refer to the same thing. uint256 seed = _generateSeed(newOriginalsSupply); // Increment the supply per original nft (max: 1) totalSupply[seed] = totalSupply[seed].add(1); assert(totalSupply[seed] == 1); // Update total originals minted originalsMinted = newOriginalsSupply; _mint(msg.sender, seed, 1, ""); emit MintOriginal(msg.sender, seed, newOriginalsSupply); return seed; } /** * @dev Function to mint prints from an existing seed. Msg.value must be sufficient. * @param seed The NFT id to mint print of * @param _owner The current owner of the seed */ function mintPrint(uint256 seed, address payable _owner) external payable onlyWhenMintPrintEnabled nonReentrant returns (uint256) { // Confirm id is a seedId and belongs to _owner require(isSeedId(seed) == true, "Invalid seed id"); // Confirm seed belongs to _owner require(balanceOf(_owner, seed) == 1, "Incorrect seed owner"); // Spam-prevention: restrict msg.sender to only external accounts for an initial mintPrint period if (msg.sender != tx.origin) { require(_contractMintPrintEnabled == true, "Contracts not allowed to mintPrint"); } // Derive print tokenId from seed uint256 tokenId = getPrintTokenIdFromSeed(seed); // Increment supply to compute current print price uint256 newSupply = totalSupply[tokenId].add(1); // Confirm newSupply does not exceed max require(newSupply <= MAX_PRINT_SUPPLY, "Maximum supply exceeded"); // Get price to mint the next print uint256 printPrice = getPrintPrice(newSupply); require(msg.value >= printPrice, "Insufficient funds"); totalSupply[tokenId] = newSupply; // Reserve cut is amount that will go towards reserve for burn at new supply uint256 reserveCut = getBurnPrice(newSupply); // Update reserve balance reserve = reserve.add(reserveCut); // Extract % for seed owner from difference between mintPrint cost and amount held for reserve uint256 seedOwnerRoyalty = _getSeedOwnerCut(printPrice.sub(reserveCut)); // Mint token _mint(msg.sender, tokenId, 1, ""); // Disburse royalties if (seedOwnerRoyalty > 0) { _distributeRoyalty(seed, _owner, seedOwnerRoyalty); } // If buyer sent extra ETH as padding in case another purchase was made they are refunded _refundSender(printPrice); emit PrintMinted(msg.sender, tokenId, seed, printPrice, getPrintPrice(newSupply.add(1)), reserveCut, newSupply, seedOwnerRoyalty, reserve, _owner); return tokenId; } /** * @dev Function to burn a print * @param seed The seed for the print to burn. * @param minimumSupply The minimum token supply for burn to succeed, this is a way to set slippage. * Set to 1 to allow burn to go through no matter what the price is. */ function burnPrint(uint256 seed, uint256 minimumSupply) external onlyWhenBurnPrintEnabled nonReentrant { // Confirm is valid seed id require(isSeedId(seed) == true, "Invalid seed id"); // Derive token Id from seed uint256 tokenId = getPrintTokenIdFromSeed(seed); // Supply must meet user's minimum threshold uint256 oldSupply = totalSupply[tokenId]; require(oldSupply >= minimumSupply, 'Min supply not met'); // burnPrice is the amount of ETH returned for burning this print uint256 burnPrice = getBurnPrice(oldSupply); uint256 newSupply = totalSupply[tokenId].sub(1); totalSupply[tokenId] = newSupply; // Update reserve balances reserve = reserve.sub(burnPrice); _burn(msg.sender, tokenId, 1); // Disburse funds msg.sender.sendValue(burnPrice); emit PrintBurned(msg.sender, tokenId, seed, burnPrice, getPrintPrice(oldSupply), getBurnPrice(newSupply), newSupply, reserve); } /***********************************| | Public Getters - Pricing | |__________________________________*/ /** * @dev Function to get print price * @param printNumber the print number of the print Ex. if there are 2 existing prints, and you want to get the * next print price, then this should be 3 as you are getting the price to mint the 3rd print */ function getPrintPrice(uint256 printNumber) public pure returns (uint256 price) { uint256 decimals = 10 ** SIG_DIGITS; // For prints 0-100, exponent value is < 0.001 if (printNumber <= 100) { price = 0; } else if (printNumber < B) { // 10/A ^ (B - X) price = (10 ** ( B.sub(printNumber) )).mul(decimals).div(A ** ( B.sub(printNumber))); } else if (printNumber == B) { // A/10 ^ 0 == 1 price = decimals; // price = decimals * (A ^ 0) } else { // A/10 ^ (X - B) price = (A ** ( printNumber.sub(B) )).mul(decimals).div(10 ** ( printNumber.sub(B) )); } // += C*X price = price.add(C.mul(printNumber)); // Convert to wei price = price.mul(1 ether).div(decimals); } /** * @dev Function to return amount of funds received when burned * @param supply the supply of prints before burning. Ex. if there are 2 existing prints, to get the funds * receive on burn the supply should be 2 */ function getBurnPrice(uint256 supply) public pure returns (uint256 price) { uint256 printPrice = getPrintPrice(supply); // 84 % of print price price = printPrice.mul(84).div(100); } /** * @dev Function to get prices by supply * @param supply the supply of prints before burning. Ex. if there are 2 existing prints, to get the funds * receive on burn the supply should be 2 */ function getPricesBySupply(uint256 supply) public pure returns (uint256 printPrice, uint256 nextPrintPrice, uint256 burnPrice, uint256 nextBurnPrice) { printPrice = getPrintPrice(supply); nextPrintPrice = getPrintPrice(supply + 1); burnPrice = getBurnPrice(supply); nextBurnPrice = getBurnPrice(supply + 1); } /** * @dev Function to get prices & supply by seed * @param seed The original NFT token id */ function getPricesBySeed(uint256 seed) external view returns (uint256 printPrice, uint256 nextPrintPrice, uint256 burnPrice, uint256 nextBurnPrice, uint256 supply) { supply = seedToPrintsSupply(seed); (printPrice, nextPrintPrice, burnPrice, nextBurnPrice) = getPricesBySupply(supply); } /***********************************| | Public Getters - Seed + Prints | |__________________________________*/ /** * @dev Get the number of prints minted for the corresponding seed * @param seed The original NFT token id */ function seedToPrintsSupply(uint256 seed) public view returns (uint256) { uint256 tokenId = getPrintTokenIdFromSeed(seed); return totalSupply[tokenId]; } /** * @dev The token id for the prints contains the original NFT id * @param seed The original NFT token id */ function getPrintTokenIdFromSeed(uint256 seed) public pure returns (uint256) { return seed | PRINTS_FLAG_BIT; } /** * @dev Return whether a tokenId is for an original * @param tokenId The original NFT token id */ function isSeedId(uint256 tokenId) public pure returns (bool) { return tokenId & PRINTS_FLAG_BIT != PRINTS_FLAG_BIT; } /***********************************| | Public Getters - Metadata | |__________________________________*/ /** * @dev Return the script section for a particular index * @param index The index of a script section */ function getScriptAtIndex(uint256 index) external view returns (string memory) { require(index < scriptCount, "Index out of bounds"); return scripts[index]; } /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * @return URI string */ function uri(uint256 _id) external override view returns (string memory) { require(totalSupply[_id] > 0, "URI query for nonexistent token"); return string(abi.encodePacked(_baseURI, _id.toString(), ".json")); } /***********************************| |Internal Functions - Generate Seed | |__________________________________*/ /** * @dev Returns a new seed * @param uniqueValue Random input for the seed generation */ function _generateSeed(uint256 uniqueValue) internal view returns (uint256) { bytes32 hash = keccak256(abi.encodePacked(block.number, blockhash(block.number.sub(1)), msg.sender, uniqueValue)); // gridLength 0-5 uint8 gridLength = uint8(hash[0]) % 15; if (gridLength > 5) gridLength = 1; // horizontalLever 0-58 uint8 horizontalLever = uint8(hash[1]) % 59; // diagonalLever 0-10 uint8 diagonalLever = uint8(hash[2]) % 11; // palette 4 0-11 uint8 palette = uint8(hash[3]) % 12; // innerShape 0-3 with rarity uint8 innerShape = uint8(hash[4]) % 4; return uint256(gridLength) << 40 | uint256(horizontalLever) << 32 | uint256(diagonalLever) << 24 | uint256(palette) << 16 | uint256(innerShape) << 8; } /***********************************| | Internal Functions - Prints | |__________________________________*/ /** * @dev Returns the part of the mintPrint fee reserved for the seed owner royalty * @param fee Amount of ETH not added to the contract reserve */ function _getSeedOwnerCut(uint256 fee) internal pure returns (uint256) { // Seed owner and Treum split royalties 50/50 return fee.div(2); } /** * @dev For mintPrint only, send remaining msg.value back to sender * @param printPrice Cost to mint current print */ function _refundSender(uint256 printPrice) internal { if (msg.value.sub(printPrice) > 0) { msg.sender.sendValue(msg.value.sub(printPrice)); } } /***********************************| | Admin | |__________________________________*/ /** * @dev Add a new section of the script * @param _script String value of script or pointer */ function addScript(string memory _script) external onlyOwner onlyUnlocked { scripts[scriptCount] = _script; scriptCount = scriptCount.add(1); } /** * @dev Overwrite a script section at a particular index * @param _script String value of script or pointer * @param index Index of the script to replace */ function updateScript(string memory _script, uint256 index) external onlyOwner onlyUnlocked { require(index < scriptCount, "Index out of bounds"); scripts[index] = _script; } /** * @dev Reset script index to zero, caller must be owner and the contract unlocked */ function resetScriptCount() external onlyOwner onlyUnlocked { scriptCount = 0; } /** * @dev Withdraw earned funds from original Nft sales and print fees. Cannot withdraw the reserve funds. */ function withdraw() external onlyOwner nonReentrant { uint256 withdrawableFunds = address(this).balance.sub(reserve); msg.sender.sendValue(withdrawableFunds); } /** * @dev Function to enable/disable original minting * @param enabled The flag to turn minting on or off */ function setMintEnabled(bool enabled) external onlyOwner { mintEnabled = enabled; } /** * @dev Function to enable/disable print minting * @param enabled The flag to turn minting on or off */ function setMintPrintEnabled(bool enabled) external onlyOwner { mintPrintEnabled = enabled; } /** * @dev Function to enable/disable print burning * @param enabled The flag to turn minting on or off */ function setBurnPrintEnabled(bool enabled) external onlyOwner { burnPrintEnabled = enabled; } /** * @dev Function to enable/disable print minting via contract * @param enabled The flag to turn contract print minting on or off */ function setContractMintPrintEnabled(bool enabled) external onlyOwner { _contractMintPrintEnabled = enabled; } /** * @dev Function to lock/unlock the on-chain metadata * @param locked The flag turn locked on */ function setLocked(bool locked) external onlyOwner onlyUnlocked { _locked = locked; } /** * @dev Function to update the base _uri for all tokens * @param newuri The base uri string */ function setURI(string memory newuri) external onlyOwner { _baseURI = newuri; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../utils/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/introspection/ERC165Checker.sol"; import "./IEulerBeatsRoyaltyReceiver.sol"; contract RoyaltyDistributor { using Address for address payable; function _distributeRoyalty( uint256 tokenId, address payable tokenOwner, uint256 royalty ) internal { require(royalty > 0, "Missing royalty"); // this logic is broken into three cases: // case 1: tokenOwner is a contract that implements RoyaltyReciever // case 2: tokenOwner is a contract but not a RoyaltyReceiver // case 3: tokenOwner is not a contract if (tokenOwner.isContract()) { if (ERC165Checker.supportsInterface(tokenOwner, IEulerBeatsRoyaltyReceiver(tokenOwner).royaltyReceived.selector)) { // case 1 require(address(this).balance >= royalty, "RoyaltyDistributor: insufficient balance"); try IEulerBeatsRoyaltyReceiver(tokenOwner).royaltyReceived{value: royalty}(address(this), tokenId, tokenOwner) returns (bytes4 response) { if (response != IEulerBeatsRoyaltyReceiver(tokenOwner).royaltyReceived.selector) { revert("IEulerBeatsRoyaltyReceiver rejected royalty"); } } catch Error(string memory reason) { revert(reason); } catch { revert("RoyaltyDistributor: royaltyReceived reverted"); } } else { // case 2 tokenOwner.sendValue(royalty); } } else { // case 3 tokenOwner.sendValue(royalty); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/introspection/ERC165.sol"; interface IEulerBeatsRoyaltyReceiver is IERC165 { /** @dev Handles the receipt of a royalty payout for the given original EulerBeat. The royalty amount is the ether in msg.value. To accept the royalty, this must return `bytes4(keccak256("royaltyReceived(address,uint256,address)"))` Implementors should take care to do the bare minimum in this function as it is called as part of the mintPrint function, and will raise the gas required for minting prints. @param tokenAddress The token address of the EulerBeats contract that the royalty was paid from @param tokenId The ID of token the royalty was paid for. This is always the original token id, not print token ids @param tokenOwner The current owner of the specified token @return `bytes4(keccak256("royaltyReceived(address,uint256,address)"))` if royalty accepted */ function royaltyReceived( address tokenAddress, uint256 tokenId, address tokenOwner ) external payable returns(bytes4); }
Get the number of prints minted for the corresponding seed seed The original NFT token id/
function seedToPrintsSupply(uint256 seed) public view returns (uint256) { uint256 tokenId = getPrintTokenIdFromSeed(seed); return totalSupply[tokenId]; }
20,063
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; /** * @title The Open Oracle Data Base Contract * @author Compound Labs, Inc. */ contract OpenOracleData { /** * @notice The event emitted when a source writes to its storage */ //event Write(address indexed source, <Key> indexed key, string kind, uint64 timestamp, <Value> value); /** * @notice Write a bunch of signed datum to the authenticated storage mapping * @param message The payload containing the timestamp, and (key, value) pairs * @param signature The cryptographic signature of the message payload, authorizing the source to write * @return The keys that were written */ //function put(bytes calldata message, bytes calldata signature) external returns (<Key> memory); /** * @notice Read a single key with a pre-defined type signature from an authenticated source * @param source The verifiable author of the data * @param key The selector for the value to return * @return The claimed Unix timestamp for the data and the encoded value (defaults to (0, 0x)) */ //function get(address source, <Key> key) external view returns (uint, <Value>); /** * @notice Recovers the source address which signed a message * @dev Comparing to a claimed address would add nothing, * as the caller could simply perform the recover and claim that address. * @param message The data that was presumably signed * @param signature The fingerprint of the data + private key * @return The source address which signed the message, presumably */ function source(bytes memory message, bytes memory signature) public pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message))); return ecrecover(hash, v, r, s); } } /** * @title The Open Oracle Price Data Contract * @notice Values stored in this contract should represent a USD price with 6 decimals precision * @author Compound Labs, Inc. */ contract OpenOraclePriceData is OpenOracleData { ///@notice The event emitted when a source writes to its storage event Write(address indexed source, string key, uint64 timestamp, uint64 value); ///@notice The event emitted when the timestamp on a price is invalid and it is not written to storage event NotWritten(uint64 priorTimestamp, uint256 messageTimestamp, uint256 blockTimestamp); ///@notice The fundamental unit of storage for a reporter source struct Datum { uint64 timestamp; uint64 value; } /** * @dev The most recent authenticated data from all sources. * This is private because dynamic mapping keys preclude auto-generated getters. */ mapping(address => mapping(string => Datum)) private data; /** * @notice Write a bunch of signed datum to the authenticated storage mapping * @param message The payload containing the timestamp, and (key, value) pairs * @param signature The cryptographic signature of the message payload, authorizing the source to write * @return The keys that were written */ function put(bytes calldata message, bytes calldata signature) external returns (string memory) { (address source, uint64 timestamp, string memory key, uint64 value) = decodeMessage(message, signature); return putInternal(source, timestamp, key, value); } function putInternal(address source, uint64 timestamp, string memory key, uint64 value) internal returns (string memory) { // Only update if newer than stored, according to source Datum storage prior = data[source][key]; if (timestamp > prior.timestamp && timestamp < block.timestamp + 60 minutes && source != address(0)) { data[source][key] = Datum(timestamp, value); emit Write(source, key, timestamp, value); } else { emit NotWritten(prior.timestamp, timestamp, block.timestamp); } return key; } function decodeMessage(bytes calldata message, bytes calldata signature) internal pure returns (address, uint64, string memory, uint64) { // Recover the source address address source = source(message, signature); // Decode the message and check the kind (string memory kind, uint64 timestamp, string memory key, uint64 value) = abi.decode(message, (string, uint64, string, uint64)); require(keccak256(abi.encodePacked(kind)) == keccak256(abi.encodePacked("prices")), "Kind of data must be 'prices'"); return (source, timestamp, key, value); } /** * @notice Read a single key from an authenticated source * @param source The verifiable author of the data * @param key The selector for the value to return * @return The claimed Unix timestamp for the data and the price value (defaults to (0, 0)) */ function get(address source, string calldata key) external view returns (uint64, uint64) { Datum storage datum = data[source][key]; return (datum.timestamp, datum.value); } /** * @notice Read only the value for a single key from an authenticated source * @param source The verifiable author of the data * @param key The selector for the value to return * @return The price value (defaults to 0) */ function getPrice(address source, string calldata key) external view returns (uint64) { return data[source][key].value; } } interface CErc20 { function underlying() external view returns (address); } contract UniswapConfig { /// @dev Describe how to interpret the fixedPrice in the TokenConfig. enum PriceSource { FIXED_ETH, /// implies the fixedPrice is a constant multiple of the ETH price (which varies) FIXED_USD, /// implies the fixedPrice is a constant multiple of the USD price (which is 1) REPORTER /// implies the price is set by the reporter } /// @dev Describe how the USD price should be determined for an asset. /// There should be 1 TokenConfig object for each supported asset, passed in the constructor. struct TokenConfig { address cToken; address underlying; bytes32 symbolHash; uint256 baseUnit; PriceSource priceSource; uint256 fixedPrice; address uniswapMarket; bool isUniswapReversed; } /// @notice The max number of tokens this contract is hardcoded to support /// @dev Do not change this variable without updating all the fields throughout the contract. uint public constant maxTokens = 30; /// @notice The number of tokens this contract actually supports uint public immutable numTokens; address internal immutable cToken00; address internal immutable cToken01; address internal immutable cToken02; address internal immutable cToken03; address internal immutable cToken04; address internal immutable cToken05; address internal immutable cToken06; address internal immutable cToken07; address internal immutable cToken08; address internal immutable cToken09; address internal immutable cToken10; address internal immutable cToken11; address internal immutable cToken12; address internal immutable cToken13; address internal immutable cToken14; address internal immutable cToken15; address internal immutable cToken16; address internal immutable cToken17; address internal immutable cToken18; address internal immutable cToken19; address internal immutable cToken20; address internal immutable cToken21; address internal immutable cToken22; address internal immutable cToken23; address internal immutable cToken24; address internal immutable cToken25; address internal immutable cToken26; address internal immutable cToken27; address internal immutable cToken28; address internal immutable cToken29; address internal immutable underlying00; address internal immutable underlying01; address internal immutable underlying02; address internal immutable underlying03; address internal immutable underlying04; address internal immutable underlying05; address internal immutable underlying06; address internal immutable underlying07; address internal immutable underlying08; address internal immutable underlying09; address internal immutable underlying10; address internal immutable underlying11; address internal immutable underlying12; address internal immutable underlying13; address internal immutable underlying14; address internal immutable underlying15; address internal immutable underlying16; address internal immutable underlying17; address internal immutable underlying18; address internal immutable underlying19; address internal immutable underlying20; address internal immutable underlying21; address internal immutable underlying22; address internal immutable underlying23; address internal immutable underlying24; address internal immutable underlying25; address internal immutable underlying26; address internal immutable underlying27; address internal immutable underlying28; address internal immutable underlying29; bytes32 internal immutable symbolHash00; bytes32 internal immutable symbolHash01; bytes32 internal immutable symbolHash02; bytes32 internal immutable symbolHash03; bytes32 internal immutable symbolHash04; bytes32 internal immutable symbolHash05; bytes32 internal immutable symbolHash06; bytes32 internal immutable symbolHash07; bytes32 internal immutable symbolHash08; bytes32 internal immutable symbolHash09; bytes32 internal immutable symbolHash10; bytes32 internal immutable symbolHash11; bytes32 internal immutable symbolHash12; bytes32 internal immutable symbolHash13; bytes32 internal immutable symbolHash14; bytes32 internal immutable symbolHash15; bytes32 internal immutable symbolHash16; bytes32 internal immutable symbolHash17; bytes32 internal immutable symbolHash18; bytes32 internal immutable symbolHash19; bytes32 internal immutable symbolHash20; bytes32 internal immutable symbolHash21; bytes32 internal immutable symbolHash22; bytes32 internal immutable symbolHash23; bytes32 internal immutable symbolHash24; bytes32 internal immutable symbolHash25; bytes32 internal immutable symbolHash26; bytes32 internal immutable symbolHash27; bytes32 internal immutable symbolHash28; bytes32 internal immutable symbolHash29; uint256 internal immutable baseUnit00; uint256 internal immutable baseUnit01; uint256 internal immutable baseUnit02; uint256 internal immutable baseUnit03; uint256 internal immutable baseUnit04; uint256 internal immutable baseUnit05; uint256 internal immutable baseUnit06; uint256 internal immutable baseUnit07; uint256 internal immutable baseUnit08; uint256 internal immutable baseUnit09; uint256 internal immutable baseUnit10; uint256 internal immutable baseUnit11; uint256 internal immutable baseUnit12; uint256 internal immutable baseUnit13; uint256 internal immutable baseUnit14; uint256 internal immutable baseUnit15; uint256 internal immutable baseUnit16; uint256 internal immutable baseUnit17; uint256 internal immutable baseUnit18; uint256 internal immutable baseUnit19; uint256 internal immutable baseUnit20; uint256 internal immutable baseUnit21; uint256 internal immutable baseUnit22; uint256 internal immutable baseUnit23; uint256 internal immutable baseUnit24; uint256 internal immutable baseUnit25; uint256 internal immutable baseUnit26; uint256 internal immutable baseUnit27; uint256 internal immutable baseUnit28; uint256 internal immutable baseUnit29; PriceSource internal immutable priceSource00; PriceSource internal immutable priceSource01; PriceSource internal immutable priceSource02; PriceSource internal immutable priceSource03; PriceSource internal immutable priceSource04; PriceSource internal immutable priceSource05; PriceSource internal immutable priceSource06; PriceSource internal immutable priceSource07; PriceSource internal immutable priceSource08; PriceSource internal immutable priceSource09; PriceSource internal immutable priceSource10; PriceSource internal immutable priceSource11; PriceSource internal immutable priceSource12; PriceSource internal immutable priceSource13; PriceSource internal immutable priceSource14; PriceSource internal immutable priceSource15; PriceSource internal immutable priceSource16; PriceSource internal immutable priceSource17; PriceSource internal immutable priceSource18; PriceSource internal immutable priceSource19; PriceSource internal immutable priceSource20; PriceSource internal immutable priceSource21; PriceSource internal immutable priceSource22; PriceSource internal immutable priceSource23; PriceSource internal immutable priceSource24; PriceSource internal immutable priceSource25; PriceSource internal immutable priceSource26; PriceSource internal immutable priceSource27; PriceSource internal immutable priceSource28; PriceSource internal immutable priceSource29; uint256 internal immutable fixedPrice00; uint256 internal immutable fixedPrice01; uint256 internal immutable fixedPrice02; uint256 internal immutable fixedPrice03; uint256 internal immutable fixedPrice04; uint256 internal immutable fixedPrice05; uint256 internal immutable fixedPrice06; uint256 internal immutable fixedPrice07; uint256 internal immutable fixedPrice08; uint256 internal immutable fixedPrice09; uint256 internal immutable fixedPrice10; uint256 internal immutable fixedPrice11; uint256 internal immutable fixedPrice12; uint256 internal immutable fixedPrice13; uint256 internal immutable fixedPrice14; uint256 internal immutable fixedPrice15; uint256 internal immutable fixedPrice16; uint256 internal immutable fixedPrice17; uint256 internal immutable fixedPrice18; uint256 internal immutable fixedPrice19; uint256 internal immutable fixedPrice20; uint256 internal immutable fixedPrice21; uint256 internal immutable fixedPrice22; uint256 internal immutable fixedPrice23; uint256 internal immutable fixedPrice24; uint256 internal immutable fixedPrice25; uint256 internal immutable fixedPrice26; uint256 internal immutable fixedPrice27; uint256 internal immutable fixedPrice28; uint256 internal immutable fixedPrice29; address internal immutable uniswapMarket00; address internal immutable uniswapMarket01; address internal immutable uniswapMarket02; address internal immutable uniswapMarket03; address internal immutable uniswapMarket04; address internal immutable uniswapMarket05; address internal immutable uniswapMarket06; address internal immutable uniswapMarket07; address internal immutable uniswapMarket08; address internal immutable uniswapMarket09; address internal immutable uniswapMarket10; address internal immutable uniswapMarket11; address internal immutable uniswapMarket12; address internal immutable uniswapMarket13; address internal immutable uniswapMarket14; address internal immutable uniswapMarket15; address internal immutable uniswapMarket16; address internal immutable uniswapMarket17; address internal immutable uniswapMarket18; address internal immutable uniswapMarket19; address internal immutable uniswapMarket20; address internal immutable uniswapMarket21; address internal immutable uniswapMarket22; address internal immutable uniswapMarket23; address internal immutable uniswapMarket24; address internal immutable uniswapMarket25; address internal immutable uniswapMarket26; address internal immutable uniswapMarket27; address internal immutable uniswapMarket28; address internal immutable uniswapMarket29; bool internal immutable isUniswapReversed00; bool internal immutable isUniswapReversed01; bool internal immutable isUniswapReversed02; bool internal immutable isUniswapReversed03; bool internal immutable isUniswapReversed04; bool internal immutable isUniswapReversed05; bool internal immutable isUniswapReversed06; bool internal immutable isUniswapReversed07; bool internal immutable isUniswapReversed08; bool internal immutable isUniswapReversed09; bool internal immutable isUniswapReversed10; bool internal immutable isUniswapReversed11; bool internal immutable isUniswapReversed12; bool internal immutable isUniswapReversed13; bool internal immutable isUniswapReversed14; bool internal immutable isUniswapReversed15; bool internal immutable isUniswapReversed16; bool internal immutable isUniswapReversed17; bool internal immutable isUniswapReversed18; bool internal immutable isUniswapReversed19; bool internal immutable isUniswapReversed20; bool internal immutable isUniswapReversed21; bool internal immutable isUniswapReversed22; bool internal immutable isUniswapReversed23; bool internal immutable isUniswapReversed24; bool internal immutable isUniswapReversed25; bool internal immutable isUniswapReversed26; bool internal immutable isUniswapReversed27; bool internal immutable isUniswapReversed28; bool internal immutable isUniswapReversed29; /** * @notice Construct an immutable store of configs into the contract data * @param configs The configs for the supported assets */ constructor(TokenConfig[] memory configs) public { require(configs.length <= maxTokens, "too many configs"); numTokens = configs.length; cToken00 = get(configs, 0).cToken; cToken01 = get(configs, 1).cToken; cToken02 = get(configs, 2).cToken; cToken03 = get(configs, 3).cToken; cToken04 = get(configs, 4).cToken; cToken05 = get(configs, 5).cToken; cToken06 = get(configs, 6).cToken; cToken07 = get(configs, 7).cToken; cToken08 = get(configs, 8).cToken; cToken09 = get(configs, 9).cToken; cToken10 = get(configs, 10).cToken; cToken11 = get(configs, 11).cToken; cToken12 = get(configs, 12).cToken; cToken13 = get(configs, 13).cToken; cToken14 = get(configs, 14).cToken; cToken15 = get(configs, 15).cToken; cToken16 = get(configs, 16).cToken; cToken17 = get(configs, 17).cToken; cToken18 = get(configs, 18).cToken; cToken19 = get(configs, 19).cToken; cToken20 = get(configs, 20).cToken; cToken21 = get(configs, 21).cToken; cToken22 = get(configs, 22).cToken; cToken23 = get(configs, 23).cToken; cToken24 = get(configs, 24).cToken; cToken25 = get(configs, 25).cToken; cToken26 = get(configs, 26).cToken; cToken27 = get(configs, 27).cToken; cToken28 = get(configs, 28).cToken; cToken29 = get(configs, 29).cToken; underlying00 = get(configs, 0).underlying; underlying01 = get(configs, 1).underlying; underlying02 = get(configs, 2).underlying; underlying03 = get(configs, 3).underlying; underlying04 = get(configs, 4).underlying; underlying05 = get(configs, 5).underlying; underlying06 = get(configs, 6).underlying; underlying07 = get(configs, 7).underlying; underlying08 = get(configs, 8).underlying; underlying09 = get(configs, 9).underlying; underlying10 = get(configs, 10).underlying; underlying11 = get(configs, 11).underlying; underlying12 = get(configs, 12).underlying; underlying13 = get(configs, 13).underlying; underlying14 = get(configs, 14).underlying; underlying15 = get(configs, 15).underlying; underlying16 = get(configs, 16).underlying; underlying17 = get(configs, 17).underlying; underlying18 = get(configs, 18).underlying; underlying19 = get(configs, 19).underlying; underlying20 = get(configs, 20).underlying; underlying21 = get(configs, 21).underlying; underlying22 = get(configs, 22).underlying; underlying23 = get(configs, 23).underlying; underlying24 = get(configs, 24).underlying; underlying25 = get(configs, 25).underlying; underlying26 = get(configs, 26).underlying; underlying27 = get(configs, 27).underlying; underlying28 = get(configs, 28).underlying; underlying29 = get(configs, 29).underlying; symbolHash00 = get(configs, 0).symbolHash; symbolHash01 = get(configs, 1).symbolHash; symbolHash02 = get(configs, 2).symbolHash; symbolHash03 = get(configs, 3).symbolHash; symbolHash04 = get(configs, 4).symbolHash; symbolHash05 = get(configs, 5).symbolHash; symbolHash06 = get(configs, 6).symbolHash; symbolHash07 = get(configs, 7).symbolHash; symbolHash08 = get(configs, 8).symbolHash; symbolHash09 = get(configs, 9).symbolHash; symbolHash10 = get(configs, 10).symbolHash; symbolHash11 = get(configs, 11).symbolHash; symbolHash12 = get(configs, 12).symbolHash; symbolHash13 = get(configs, 13).symbolHash; symbolHash14 = get(configs, 14).symbolHash; symbolHash15 = get(configs, 15).symbolHash; symbolHash16 = get(configs, 16).symbolHash; symbolHash17 = get(configs, 17).symbolHash; symbolHash18 = get(configs, 18).symbolHash; symbolHash19 = get(configs, 19).symbolHash; symbolHash20 = get(configs, 20).symbolHash; symbolHash21 = get(configs, 21).symbolHash; symbolHash22 = get(configs, 22).symbolHash; symbolHash23 = get(configs, 23).symbolHash; symbolHash24 = get(configs, 24).symbolHash; symbolHash25 = get(configs, 25).symbolHash; symbolHash26 = get(configs, 26).symbolHash; symbolHash27 = get(configs, 27).symbolHash; symbolHash28 = get(configs, 28).symbolHash; symbolHash29 = get(configs, 29).symbolHash; baseUnit00 = get(configs, 0).baseUnit; baseUnit01 = get(configs, 1).baseUnit; baseUnit02 = get(configs, 2).baseUnit; baseUnit03 = get(configs, 3).baseUnit; baseUnit04 = get(configs, 4).baseUnit; baseUnit05 = get(configs, 5).baseUnit; baseUnit06 = get(configs, 6).baseUnit; baseUnit07 = get(configs, 7).baseUnit; baseUnit08 = get(configs, 8).baseUnit; baseUnit09 = get(configs, 9).baseUnit; baseUnit10 = get(configs, 10).baseUnit; baseUnit11 = get(configs, 11).baseUnit; baseUnit12 = get(configs, 12).baseUnit; baseUnit13 = get(configs, 13).baseUnit; baseUnit14 = get(configs, 14).baseUnit; baseUnit15 = get(configs, 15).baseUnit; baseUnit16 = get(configs, 16).baseUnit; baseUnit17 = get(configs, 17).baseUnit; baseUnit18 = get(configs, 18).baseUnit; baseUnit19 = get(configs, 19).baseUnit; baseUnit20 = get(configs, 20).baseUnit; baseUnit21 = get(configs, 21).baseUnit; baseUnit22 = get(configs, 22).baseUnit; baseUnit23 = get(configs, 23).baseUnit; baseUnit24 = get(configs, 24).baseUnit; baseUnit25 = get(configs, 25).baseUnit; baseUnit26 = get(configs, 26).baseUnit; baseUnit27 = get(configs, 27).baseUnit; baseUnit28 = get(configs, 28).baseUnit; baseUnit29 = get(configs, 29).baseUnit; priceSource00 = get(configs, 0).priceSource; priceSource01 = get(configs, 1).priceSource; priceSource02 = get(configs, 2).priceSource; priceSource03 = get(configs, 3).priceSource; priceSource04 = get(configs, 4).priceSource; priceSource05 = get(configs, 5).priceSource; priceSource06 = get(configs, 6).priceSource; priceSource07 = get(configs, 7).priceSource; priceSource08 = get(configs, 8).priceSource; priceSource09 = get(configs, 9).priceSource; priceSource10 = get(configs, 10).priceSource; priceSource11 = get(configs, 11).priceSource; priceSource12 = get(configs, 12).priceSource; priceSource13 = get(configs, 13).priceSource; priceSource14 = get(configs, 14).priceSource; priceSource15 = get(configs, 15).priceSource; priceSource16 = get(configs, 16).priceSource; priceSource17 = get(configs, 17).priceSource; priceSource18 = get(configs, 18).priceSource; priceSource19 = get(configs, 19).priceSource; priceSource20 = get(configs, 20).priceSource; priceSource21 = get(configs, 21).priceSource; priceSource22 = get(configs, 22).priceSource; priceSource23 = get(configs, 23).priceSource; priceSource24 = get(configs, 24).priceSource; priceSource25 = get(configs, 25).priceSource; priceSource26 = get(configs, 26).priceSource; priceSource27 = get(configs, 27).priceSource; priceSource28 = get(configs, 28).priceSource; priceSource29 = get(configs, 29).priceSource; fixedPrice00 = get(configs, 0).fixedPrice; fixedPrice01 = get(configs, 1).fixedPrice; fixedPrice02 = get(configs, 2).fixedPrice; fixedPrice03 = get(configs, 3).fixedPrice; fixedPrice04 = get(configs, 4).fixedPrice; fixedPrice05 = get(configs, 5).fixedPrice; fixedPrice06 = get(configs, 6).fixedPrice; fixedPrice07 = get(configs, 7).fixedPrice; fixedPrice08 = get(configs, 8).fixedPrice; fixedPrice09 = get(configs, 9).fixedPrice; fixedPrice10 = get(configs, 10).fixedPrice; fixedPrice11 = get(configs, 11).fixedPrice; fixedPrice12 = get(configs, 12).fixedPrice; fixedPrice13 = get(configs, 13).fixedPrice; fixedPrice14 = get(configs, 14).fixedPrice; fixedPrice15 = get(configs, 15).fixedPrice; fixedPrice16 = get(configs, 16).fixedPrice; fixedPrice17 = get(configs, 17).fixedPrice; fixedPrice18 = get(configs, 18).fixedPrice; fixedPrice19 = get(configs, 19).fixedPrice; fixedPrice20 = get(configs, 20).fixedPrice; fixedPrice21 = get(configs, 21).fixedPrice; fixedPrice22 = get(configs, 22).fixedPrice; fixedPrice23 = get(configs, 23).fixedPrice; fixedPrice24 = get(configs, 24).fixedPrice; fixedPrice25 = get(configs, 25).fixedPrice; fixedPrice26 = get(configs, 26).fixedPrice; fixedPrice27 = get(configs, 27).fixedPrice; fixedPrice28 = get(configs, 28).fixedPrice; fixedPrice29 = get(configs, 29).fixedPrice; uniswapMarket00 = get(configs, 0).uniswapMarket; uniswapMarket01 = get(configs, 1).uniswapMarket; uniswapMarket02 = get(configs, 2).uniswapMarket; uniswapMarket03 = get(configs, 3).uniswapMarket; uniswapMarket04 = get(configs, 4).uniswapMarket; uniswapMarket05 = get(configs, 5).uniswapMarket; uniswapMarket06 = get(configs, 6).uniswapMarket; uniswapMarket07 = get(configs, 7).uniswapMarket; uniswapMarket08 = get(configs, 8).uniswapMarket; uniswapMarket09 = get(configs, 9).uniswapMarket; uniswapMarket10 = get(configs, 10).uniswapMarket; uniswapMarket11 = get(configs, 11).uniswapMarket; uniswapMarket12 = get(configs, 12).uniswapMarket; uniswapMarket13 = get(configs, 13).uniswapMarket; uniswapMarket14 = get(configs, 14).uniswapMarket; uniswapMarket15 = get(configs, 15).uniswapMarket; uniswapMarket16 = get(configs, 16).uniswapMarket; uniswapMarket17 = get(configs, 17).uniswapMarket; uniswapMarket18 = get(configs, 18).uniswapMarket; uniswapMarket19 = get(configs, 19).uniswapMarket; uniswapMarket20 = get(configs, 20).uniswapMarket; uniswapMarket21 = get(configs, 21).uniswapMarket; uniswapMarket22 = get(configs, 22).uniswapMarket; uniswapMarket23 = get(configs, 23).uniswapMarket; uniswapMarket24 = get(configs, 24).uniswapMarket; uniswapMarket25 = get(configs, 25).uniswapMarket; uniswapMarket26 = get(configs, 26).uniswapMarket; uniswapMarket27 = get(configs, 27).uniswapMarket; uniswapMarket28 = get(configs, 28).uniswapMarket; uniswapMarket29 = get(configs, 29).uniswapMarket; isUniswapReversed00 = get(configs, 0).isUniswapReversed; isUniswapReversed01 = get(configs, 1).isUniswapReversed; isUniswapReversed02 = get(configs, 2).isUniswapReversed; isUniswapReversed03 = get(configs, 3).isUniswapReversed; isUniswapReversed04 = get(configs, 4).isUniswapReversed; isUniswapReversed05 = get(configs, 5).isUniswapReversed; isUniswapReversed06 = get(configs, 6).isUniswapReversed; isUniswapReversed07 = get(configs, 7).isUniswapReversed; isUniswapReversed08 = get(configs, 8).isUniswapReversed; isUniswapReversed09 = get(configs, 9).isUniswapReversed; isUniswapReversed10 = get(configs, 10).isUniswapReversed; isUniswapReversed11 = get(configs, 11).isUniswapReversed; isUniswapReversed12 = get(configs, 12).isUniswapReversed; isUniswapReversed13 = get(configs, 13).isUniswapReversed; isUniswapReversed14 = get(configs, 14).isUniswapReversed; isUniswapReversed15 = get(configs, 15).isUniswapReversed; isUniswapReversed16 = get(configs, 16).isUniswapReversed; isUniswapReversed17 = get(configs, 17).isUniswapReversed; isUniswapReversed18 = get(configs, 18).isUniswapReversed; isUniswapReversed19 = get(configs, 19).isUniswapReversed; isUniswapReversed20 = get(configs, 20).isUniswapReversed; isUniswapReversed21 = get(configs, 21).isUniswapReversed; isUniswapReversed22 = get(configs, 22).isUniswapReversed; isUniswapReversed23 = get(configs, 23).isUniswapReversed; isUniswapReversed24 = get(configs, 24).isUniswapReversed; isUniswapReversed25 = get(configs, 25).isUniswapReversed; isUniswapReversed26 = get(configs, 26).isUniswapReversed; isUniswapReversed27 = get(configs, 27).isUniswapReversed; isUniswapReversed28 = get(configs, 28).isUniswapReversed; isUniswapReversed29 = get(configs, 29).isUniswapReversed; } function get(TokenConfig[] memory configs, uint i) internal pure returns (TokenConfig memory) { if (i < configs.length) return configs[i]; return TokenConfig({ cToken: address(0), underlying: address(0), symbolHash: bytes32(0), baseUnit: uint256(0), priceSource: PriceSource(0), fixedPrice: uint256(0), uniswapMarket: address(0), isUniswapReversed: false }); } function getCTokenIndex(address cToken) internal view returns (uint) { if (cToken == cToken00) return 0; if (cToken == cToken01) return 1; if (cToken == cToken02) return 2; if (cToken == cToken03) return 3; if (cToken == cToken04) return 4; if (cToken == cToken05) return 5; if (cToken == cToken06) return 6; if (cToken == cToken07) return 7; if (cToken == cToken08) return 8; if (cToken == cToken09) return 9; if (cToken == cToken10) return 10; if (cToken == cToken11) return 11; if (cToken == cToken12) return 12; if (cToken == cToken13) return 13; if (cToken == cToken14) return 14; if (cToken == cToken15) return 15; if (cToken == cToken16) return 16; if (cToken == cToken17) return 17; if (cToken == cToken18) return 18; if (cToken == cToken19) return 19; if (cToken == cToken20) return 20; if (cToken == cToken21) return 21; if (cToken == cToken22) return 22; if (cToken == cToken23) return 23; if (cToken == cToken24) return 24; if (cToken == cToken25) return 25; if (cToken == cToken26) return 26; if (cToken == cToken27) return 27; if (cToken == cToken28) return 28; if (cToken == cToken29) return 29; return uint(-1); } function getUnderlyingIndex(address underlying) internal view returns (uint) { if (underlying == underlying00) return 0; if (underlying == underlying01) return 1; if (underlying == underlying02) return 2; if (underlying == underlying03) return 3; if (underlying == underlying04) return 4; if (underlying == underlying05) return 5; if (underlying == underlying06) return 6; if (underlying == underlying07) return 7; if (underlying == underlying08) return 8; if (underlying == underlying09) return 9; if (underlying == underlying10) return 10; if (underlying == underlying11) return 11; if (underlying == underlying12) return 12; if (underlying == underlying13) return 13; if (underlying == underlying14) return 14; if (underlying == underlying15) return 15; if (underlying == underlying16) return 16; if (underlying == underlying17) return 17; if (underlying == underlying18) return 18; if (underlying == underlying19) return 19; if (underlying == underlying20) return 20; if (underlying == underlying21) return 21; if (underlying == underlying22) return 22; if (underlying == underlying23) return 23; if (underlying == underlying24) return 24; if (underlying == underlying25) return 25; if (underlying == underlying26) return 26; if (underlying == underlying27) return 27; if (underlying == underlying28) return 28; if (underlying == underlying29) return 29; return uint(-1); } function getSymbolHashIndex(bytes32 symbolHash) internal view returns (uint) { if (symbolHash == symbolHash00) return 0; if (symbolHash == symbolHash01) return 1; if (symbolHash == symbolHash02) return 2; if (symbolHash == symbolHash03) return 3; if (symbolHash == symbolHash04) return 4; if (symbolHash == symbolHash05) return 5; if (symbolHash == symbolHash06) return 6; if (symbolHash == symbolHash07) return 7; if (symbolHash == symbolHash08) return 8; if (symbolHash == symbolHash09) return 9; if (symbolHash == symbolHash10) return 10; if (symbolHash == symbolHash11) return 11; if (symbolHash == symbolHash12) return 12; if (symbolHash == symbolHash13) return 13; if (symbolHash == symbolHash14) return 14; if (symbolHash == symbolHash15) return 15; if (symbolHash == symbolHash16) return 16; if (symbolHash == symbolHash17) return 17; if (symbolHash == symbolHash18) return 18; if (symbolHash == symbolHash19) return 19; if (symbolHash == symbolHash20) return 20; if (symbolHash == symbolHash21) return 21; if (symbolHash == symbolHash22) return 22; if (symbolHash == symbolHash23) return 23; if (symbolHash == symbolHash24) return 24; if (symbolHash == symbolHash25) return 25; if (symbolHash == symbolHash26) return 26; if (symbolHash == symbolHash27) return 27; if (symbolHash == symbolHash28) return 28; if (symbolHash == symbolHash29) return 29; return uint(-1); } /** * @notice Get the i-th config, according to the order they were passed in originally * @param i The index of the config to get * @return The config object */ function getTokenConfig(uint i) public view returns (TokenConfig memory) { require(i < numTokens, "token config not found"); if (i == 0) return TokenConfig({cToken: cToken00, underlying: underlying00, symbolHash: symbolHash00, baseUnit: baseUnit00, priceSource: priceSource00, fixedPrice: fixedPrice00, uniswapMarket: uniswapMarket00, isUniswapReversed: isUniswapReversed00}); if (i == 1) return TokenConfig({cToken: cToken01, underlying: underlying01, symbolHash: symbolHash01, baseUnit: baseUnit01, priceSource: priceSource01, fixedPrice: fixedPrice01, uniswapMarket: uniswapMarket01, isUniswapReversed: isUniswapReversed01}); if (i == 2) return TokenConfig({cToken: cToken02, underlying: underlying02, symbolHash: symbolHash02, baseUnit: baseUnit02, priceSource: priceSource02, fixedPrice: fixedPrice02, uniswapMarket: uniswapMarket02, isUniswapReversed: isUniswapReversed02}); if (i == 3) return TokenConfig({cToken: cToken03, underlying: underlying03, symbolHash: symbolHash03, baseUnit: baseUnit03, priceSource: priceSource03, fixedPrice: fixedPrice03, uniswapMarket: uniswapMarket03, isUniswapReversed: isUniswapReversed03}); if (i == 4) return TokenConfig({cToken: cToken04, underlying: underlying04, symbolHash: symbolHash04, baseUnit: baseUnit04, priceSource: priceSource04, fixedPrice: fixedPrice04, uniswapMarket: uniswapMarket04, isUniswapReversed: isUniswapReversed04}); if (i == 5) return TokenConfig({cToken: cToken05, underlying: underlying05, symbolHash: symbolHash05, baseUnit: baseUnit05, priceSource: priceSource05, fixedPrice: fixedPrice05, uniswapMarket: uniswapMarket05, isUniswapReversed: isUniswapReversed05}); if (i == 6) return TokenConfig({cToken: cToken06, underlying: underlying06, symbolHash: symbolHash06, baseUnit: baseUnit06, priceSource: priceSource06, fixedPrice: fixedPrice06, uniswapMarket: uniswapMarket06, isUniswapReversed: isUniswapReversed06}); if (i == 7) return TokenConfig({cToken: cToken07, underlying: underlying07, symbolHash: symbolHash07, baseUnit: baseUnit07, priceSource: priceSource07, fixedPrice: fixedPrice07, uniswapMarket: uniswapMarket07, isUniswapReversed: isUniswapReversed07}); if (i == 8) return TokenConfig({cToken: cToken08, underlying: underlying08, symbolHash: symbolHash08, baseUnit: baseUnit08, priceSource: priceSource08, fixedPrice: fixedPrice08, uniswapMarket: uniswapMarket08, isUniswapReversed: isUniswapReversed08}); if (i == 9) return TokenConfig({cToken: cToken09, underlying: underlying09, symbolHash: symbolHash09, baseUnit: baseUnit09, priceSource: priceSource09, fixedPrice: fixedPrice09, uniswapMarket: uniswapMarket09, isUniswapReversed: isUniswapReversed09}); if (i == 10) return TokenConfig({cToken: cToken10, underlying: underlying10, symbolHash: symbolHash10, baseUnit: baseUnit10, priceSource: priceSource10, fixedPrice: fixedPrice10, uniswapMarket: uniswapMarket10, isUniswapReversed: isUniswapReversed10}); if (i == 11) return TokenConfig({cToken: cToken11, underlying: underlying11, symbolHash: symbolHash11, baseUnit: baseUnit11, priceSource: priceSource11, fixedPrice: fixedPrice11, uniswapMarket: uniswapMarket11, isUniswapReversed: isUniswapReversed11}); if (i == 12) return TokenConfig({cToken: cToken12, underlying: underlying12, symbolHash: symbolHash12, baseUnit: baseUnit12, priceSource: priceSource12, fixedPrice: fixedPrice12, uniswapMarket: uniswapMarket12, isUniswapReversed: isUniswapReversed12}); if (i == 13) return TokenConfig({cToken: cToken13, underlying: underlying13, symbolHash: symbolHash13, baseUnit: baseUnit13, priceSource: priceSource13, fixedPrice: fixedPrice13, uniswapMarket: uniswapMarket13, isUniswapReversed: isUniswapReversed13}); if (i == 14) return TokenConfig({cToken: cToken14, underlying: underlying14, symbolHash: symbolHash14, baseUnit: baseUnit14, priceSource: priceSource14, fixedPrice: fixedPrice14, uniswapMarket: uniswapMarket14, isUniswapReversed: isUniswapReversed14}); if (i == 15) return TokenConfig({cToken: cToken15, underlying: underlying15, symbolHash: symbolHash15, baseUnit: baseUnit15, priceSource: priceSource15, fixedPrice: fixedPrice15, uniswapMarket: uniswapMarket15, isUniswapReversed: isUniswapReversed15}); if (i == 16) return TokenConfig({cToken: cToken16, underlying: underlying16, symbolHash: symbolHash16, baseUnit: baseUnit16, priceSource: priceSource16, fixedPrice: fixedPrice16, uniswapMarket: uniswapMarket16, isUniswapReversed: isUniswapReversed16}); if (i == 17) return TokenConfig({cToken: cToken17, underlying: underlying17, symbolHash: symbolHash17, baseUnit: baseUnit17, priceSource: priceSource17, fixedPrice: fixedPrice17, uniswapMarket: uniswapMarket17, isUniswapReversed: isUniswapReversed17}); if (i == 18) return TokenConfig({cToken: cToken18, underlying: underlying18, symbolHash: symbolHash18, baseUnit: baseUnit18, priceSource: priceSource18, fixedPrice: fixedPrice18, uniswapMarket: uniswapMarket18, isUniswapReversed: isUniswapReversed18}); if (i == 19) return TokenConfig({cToken: cToken19, underlying: underlying19, symbolHash: symbolHash19, baseUnit: baseUnit19, priceSource: priceSource19, fixedPrice: fixedPrice19, uniswapMarket: uniswapMarket19, isUniswapReversed: isUniswapReversed19}); if (i == 20) return TokenConfig({cToken: cToken20, underlying: underlying20, symbolHash: symbolHash20, baseUnit: baseUnit20, priceSource: priceSource20, fixedPrice: fixedPrice20, uniswapMarket: uniswapMarket20, isUniswapReversed: isUniswapReversed20}); if (i == 21) return TokenConfig({cToken: cToken21, underlying: underlying21, symbolHash: symbolHash21, baseUnit: baseUnit21, priceSource: priceSource21, fixedPrice: fixedPrice21, uniswapMarket: uniswapMarket21, isUniswapReversed: isUniswapReversed21}); if (i == 22) return TokenConfig({cToken: cToken22, underlying: underlying22, symbolHash: symbolHash22, baseUnit: baseUnit22, priceSource: priceSource22, fixedPrice: fixedPrice22, uniswapMarket: uniswapMarket22, isUniswapReversed: isUniswapReversed22}); if (i == 23) return TokenConfig({cToken: cToken23, underlying: underlying23, symbolHash: symbolHash23, baseUnit: baseUnit23, priceSource: priceSource23, fixedPrice: fixedPrice23, uniswapMarket: uniswapMarket23, isUniswapReversed: isUniswapReversed23}); if (i == 24) return TokenConfig({cToken: cToken24, underlying: underlying24, symbolHash: symbolHash24, baseUnit: baseUnit24, priceSource: priceSource24, fixedPrice: fixedPrice24, uniswapMarket: uniswapMarket24, isUniswapReversed: isUniswapReversed24}); if (i == 25) return TokenConfig({cToken: cToken25, underlying: underlying25, symbolHash: symbolHash25, baseUnit: baseUnit25, priceSource: priceSource25, fixedPrice: fixedPrice25, uniswapMarket: uniswapMarket25, isUniswapReversed: isUniswapReversed25}); if (i == 26) return TokenConfig({cToken: cToken26, underlying: underlying26, symbolHash: symbolHash26, baseUnit: baseUnit26, priceSource: priceSource26, fixedPrice: fixedPrice26, uniswapMarket: uniswapMarket26, isUniswapReversed: isUniswapReversed26}); if (i == 27) return TokenConfig({cToken: cToken27, underlying: underlying27, symbolHash: symbolHash27, baseUnit: baseUnit27, priceSource: priceSource27, fixedPrice: fixedPrice27, uniswapMarket: uniswapMarket27, isUniswapReversed: isUniswapReversed27}); if (i == 28) return TokenConfig({cToken: cToken28, underlying: underlying28, symbolHash: symbolHash28, baseUnit: baseUnit28, priceSource: priceSource28, fixedPrice: fixedPrice28, uniswapMarket: uniswapMarket28, isUniswapReversed: isUniswapReversed28}); if (i == 29) return TokenConfig({cToken: cToken29, underlying: underlying29, symbolHash: symbolHash29, baseUnit: baseUnit29, priceSource: priceSource29, fixedPrice: fixedPrice29, uniswapMarket: uniswapMarket29, isUniswapReversed: isUniswapReversed29}); } /** * @notice Get the config for symbol * @param symbol The symbol of the config to get * @return The config object */ function getTokenConfigBySymbol(string memory symbol) public view returns (TokenConfig memory) { return getTokenConfigBySymbolHash(keccak256(abi.encodePacked(symbol))); } /** * @notice Get the config for the symbolHash * @param symbolHash The keccack256 of the symbol of the config to get * @return The config object */ function getTokenConfigBySymbolHash(bytes32 symbolHash) public view returns (TokenConfig memory) { uint index = getSymbolHashIndex(symbolHash); if (index != uint(-1)) { return getTokenConfig(index); } revert("token config not found"); } /** * @notice Get the config for the cToken * @dev If a config for the cToken is not found, falls back to searching for the underlying. * @param cToken The address of the cToken of the config to get * @return The config object */ function getTokenConfigByCToken(address cToken) public view returns (TokenConfig memory) { uint index = getCTokenIndex(cToken); if (index != uint(-1)) { return getTokenConfig(index); } return getTokenConfigByUnderlying(CErc20(cToken).underlying()); } /** * @notice Get the config for an underlying asset * @param underlying The address of the underlying asset of the config to get * @return The config object */ function getTokenConfigByUnderlying(address underlying) public view returns (TokenConfig memory) { uint index = getUnderlyingIndex(underlying); if (index != uint(-1)) { return getTokenConfig(index); } revert("token config not found"); } } // Based on code from https://github.com/Uniswap/uniswap-v2-periphery // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // returns a uq112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << 112) / denominator); } // decode a uq112x112 into a uint with 18 decimals of precision function decode112with18(uq112x112 memory self) internal pure returns (uint) { // we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous // instead, get close to: // (x * 1e18) >> 112 // without risk of overflowing, e.g.: // (x) / 2 ** (112 - lg(1e18)) return uint(self._x) / 5192296858534827; } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); } struct Observation { uint timestamp; uint acc; } contract UniswapAnchoredView is UniswapConfig { using FixedPoint for *; /// @notice The Open Oracle Price Data contract OpenOraclePriceData public immutable priceData; /// @notice The number of wei in 1 ETH uint public constant ethBaseUnit = 1e18; /// @notice A common scaling factor to maintain precision uint public constant expScale = 1e18; /// @notice The Open Oracle Reporter address public immutable reporter; /// @notice The highest ratio of the new price to the anchor price that will still trigger the price to be updated uint public immutable upperBoundAnchorRatio; /// @notice The lowest ratio of the new price to the anchor price that will still trigger the price to be updated uint public immutable lowerBoundAnchorRatio; /// @notice The minimum amount of time in seconds required for the old uniswap price accumulator to be replaced uint public immutable anchorPeriod; /// @notice Official prices by symbol hash mapping(bytes32 => uint) public prices; /// @notice Circuit breaker for using anchor price oracle directly, ignoring reporter bool public reporterInvalidated; /// @notice The old observation for each symbolHash mapping(bytes32 => Observation) public oldObservations; /// @notice The new observation for each symbolHash mapping(bytes32 => Observation) public newObservations; /// @notice The event emitted when new prices are posted but the stored price is not updated due to the anchor event PriceGuarded(string symbol, uint reporter, uint anchor); /// @notice The event emitted when the stored price is updated event PriceUpdated(string symbol, uint price); /// @notice The event emitted when anchor price is updated event AnchorPriceUpdated(string symbol, uint anchorPrice, uint oldTimestamp, uint newTimestamp); /// @notice The event emitted when the uniswap window changes event UniswapWindowUpdated(bytes32 indexed symbolHash, uint oldTimestamp, uint newTimestamp, uint oldPrice, uint newPrice); /// @notice The event emitted when reporter invalidates itself event ReporterInvalidated(address reporter); bytes32 constant ethHash = keccak256(abi.encodePacked("ETH")); bytes32 constant rotateHash = keccak256(abi.encodePacked("rotate")); /** * @notice Construct a uniswap anchored view for a set of token configurations * @dev Note that to avoid immature TWAPs, the system must run for at least a single anchorPeriod before using. * @param reporter_ The reporter whose prices are to be used * @param anchorToleranceMantissa_ The percentage tolerance that the reporter may deviate from the uniswap anchor * @param anchorPeriod_ The minimum amount of time required for the old uniswap price accumulator to be replaced * @param configs The static token configurations which define what prices are supported and how */ constructor(OpenOraclePriceData priceData_, address reporter_, uint anchorToleranceMantissa_, uint anchorPeriod_, TokenConfig[] memory configs) UniswapConfig(configs) public { priceData = priceData_; reporter = reporter_; anchorPeriod = anchorPeriod_; // Allow the tolerance to be whatever the deployer chooses, but prevent under/overflow (and prices from being 0) upperBoundAnchorRatio = anchorToleranceMantissa_ > uint(-1) - 100e16 ? uint(-1) : 100e16 + anchorToleranceMantissa_; lowerBoundAnchorRatio = anchorToleranceMantissa_ < 100e16 ? 100e16 - anchorToleranceMantissa_ : 1; for (uint i = 0; i < configs.length; i++) { TokenConfig memory config = configs[i]; require(config.baseUnit > 0, "baseUnit must be greater than zero"); address uniswapMarket = config.uniswapMarket; if (config.priceSource == PriceSource.REPORTER) { require(uniswapMarket != address(0), "reported prices must have an anchor"); bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); oldObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].timestamp = block.timestamp; oldObservations[symbolHash].acc = cumulativePrice; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(symbolHash, block.timestamp, block.timestamp, cumulativePrice, cumulativePrice); } else { require(uniswapMarket == address(0), "only reported prices utilize an anchor"); } } } /** * @notice Get the official price for a symbol * @param symbol The symbol to fetch the price of * @return Price denominated in USD, with 6 decimals */ function price(string memory symbol) external view returns (uint) { TokenConfig memory config = getTokenConfigBySymbol(symbol); return priceInternal(config); } function priceInternal(TokenConfig memory config) internal view returns (uint) { if (config.priceSource == PriceSource.REPORTER) return prices[config.symbolHash]; if (config.priceSource == PriceSource.FIXED_USD) return config.fixedPrice; if (config.priceSource == PriceSource.FIXED_ETH) { uint usdPerEth = prices[ethHash]; require(usdPerEth > 0, "ETH price not set, cannot convert to dollars"); return mul(usdPerEth, config.fixedPrice) / ethBaseUnit; } } /** * @notice Get the underlying price of a cToken * @dev Implements the PriceOracle interface for Compound v2. * @param cToken The cToken address for price retrieval * @return Price denominated in USD, with 18 decimals, for the given cToken address */ function getUnderlyingPrice(address cToken) external view returns (uint) { TokenConfig memory config = getTokenConfigByCToken(cToken); // Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit) // Since the prices in this view have 6 decimals, we must scale them by 1e(36 - 6 - baseUnit) return mul(1e30, priceInternal(config)) / config.baseUnit; } /** * @notice Post open oracle reporter prices, and recalculate stored price by comparing to anchor * @dev We let anyone pay to post anything, but only prices from configured reporter will be stored in the view. * @param messages The messages to post to the oracle * @param signatures The signatures for the corresponding messages * @param symbols The symbols to compare to anchor for authoritative reading */ function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external { require(messages.length == signatures.length, "messages and signatures must be 1:1"); // Save the prices for (uint i = 0; i < messages.length; i++) { priceData.put(messages[i], signatures[i]); } uint ethPrice = fetchEthPrice(); // Try to update the view storage for (uint i = 0; i < symbols.length; i++) { postPriceInternal(symbols[i], ethPrice); } } function postPriceInternal(string memory symbol, uint ethPrice) internal { TokenConfig memory config = getTokenConfigBySymbol(symbol); require(config.priceSource == PriceSource.REPORTER, "only reporter prices get posted"); bytes32 symbolHash = keccak256(abi.encodePacked(symbol)); uint reporterPrice = priceData.getPrice(reporter, symbol); uint anchorPrice; if (symbolHash == ethHash) { anchorPrice = ethPrice; } else { anchorPrice = fetchAnchorPrice(symbol, config, ethPrice); } if (reporterInvalidated) { prices[symbolHash] = anchorPrice; emit PriceUpdated(symbol, anchorPrice); } else if (isWithinAnchor(reporterPrice, anchorPrice)) { prices[symbolHash] = reporterPrice; emit PriceUpdated(symbol, reporterPrice); } else { emit PriceGuarded(symbol, reporterPrice, anchorPrice); } } function isWithinAnchor(uint reporterPrice, uint anchorPrice) internal view returns (bool) { if (reporterPrice > 0) { uint anchorRatio = mul(anchorPrice, 100e16) / reporterPrice; return anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio; } return false; } /** * @dev Fetches the current token/eth price accumulator from uniswap. */ function currentCumulativePrice(TokenConfig memory config) internal view returns (uint) { (uint cumulativePrice0, uint cumulativePrice1,) = UniswapV2OracleLibrary.currentCumulativePrices(config.uniswapMarket); if (config.isUniswapReversed) { return cumulativePrice1; } else { return cumulativePrice0; } } /** * @dev Fetches the current eth/usd price from uniswap, with 6 decimals of precision. * Conversion factor is 1e18 for eth/usdc market, since we decode uniswap price statically with 18 decimals. */ function fetchEthPrice() internal returns (uint) { return fetchAnchorPrice("ETH", getTokenConfigBySymbolHash(ethHash), ethBaseUnit); } /** * @dev Fetches the current token/usd price from uniswap, with 6 decimals of precision. * @param conversionFactor 1e18 if seeking the ETH price, and a 6 decimal ETH-USDC price in the case of other assets */ function fetchAnchorPrice(string memory symbol, TokenConfig memory config, uint conversionFactor) internal virtual returns (uint) { (uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config); // This should be impossible, but better safe than sorry require(block.timestamp > oldTimestamp, "now must come after before"); uint timeElapsed = block.timestamp - oldTimestamp; // Calculate uniswap time-weighted average price // Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190 FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)); uint rawUniswapPriceMantissa = priceAverage.decode112with18(); uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, conversionFactor); uint anchorPrice; // Adjust rawUniswapPrice according to the units of the non-ETH asset // In the case of ETH, we would have to scale by 1e6 / USDC_UNITS, but since baseUnit2 is 1e6 (USDC), it cancels if (config.isUniswapReversed) { // unscaledPriceMantissa * ethBaseUnit / config.baseUnit / expScale, but we simplify bc ethBaseUnit == expScale anchorPrice = unscaledPriceMantissa / config.baseUnit; } else { anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale; } emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp); return anchorPrice; } /** * @dev Get time-weighted average prices for a token at the current timestamp. * Update new and old observations of lagging window if period elapsed. */ function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) { bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); Observation memory newObservation = newObservations[symbolHash]; // Update new and old observations if elapsed time is greater than or equal to anchor period uint timeElapsed = block.timestamp - newObservation.timestamp; if (timeElapsed >= anchorPeriod) { oldObservations[symbolHash].timestamp = newObservation.timestamp; oldObservations[symbolHash].acc = newObservation.acc; newObservations[symbolHash].timestamp = block.timestamp; newObservations[symbolHash].acc = cumulativePrice; emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice); } return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp); } /** * @notice Invalidate the reporter, and fall back to using anchor directly in all cases * @dev Only the reporter may sign a message which allows it to invalidate itself. * To be used in cases of emergency, if the reporter thinks their key may be compromised. * @param message The data that was presumably signed * @param signature The fingerprint of the data + private key */ function invalidateReporter(bytes memory message, bytes memory signature) external { (string memory decodedMessage, ) = abi.decode(message, (string, address)); require(keccak256(abi.encodePacked(decodedMessage)) == rotateHash, "invalid message must be 'rotate'"); require(source(message, signature) == reporter, "invalidation message must come from the reporter"); reporterInvalidated = true; emit ReporterInvalidated(reporter); } /** * @notice Recovers the source address which signed a message * @dev Comparing to a claimed address would add nothing, * as the caller could simply perform the recover and claim that address. * @param message The data that was presumably signed * @param signature The fingerprint of the data + private key * @return The source address which signed the message, presumably */ function source(bytes memory message, bytes memory signature) public pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message))); return ecrecover(hash, v, r, s); } /// @dev Overflow proof multiplication function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "multiplication overflow"); return c; } } interface IPriceOracle { function assetPrices(address) external view returns (uint256); function getPrices(address) external view returns (uint256); } /** * @title Open Oracle Adapater for v1 Interface * @author Compound Labs, Inc. */ contract OpenOracleV1 is IPriceOracle { UniswapAnchoredView public immutable openOracleView; address public immutable weth; constructor(UniswapAnchoredView openOracleView_, address weth_) public { openOracleView = openOracleView_; weth = weth_; } function getPrices(address asset) public view override returns (uint256) { UniswapConfig.TokenConfig memory ethConfig = openOracleView.getTokenConfigBySymbol("ETH"); UniswapConfig.TokenConfig memory cTokenConfig; if (asset == weth) { cTokenConfig = ethConfig; } else { cTokenConfig = openOracleView.getTokenConfigByUnderlying(asset); } uint tokenPrice = openOracleView.getUnderlyingPrice(cTokenConfig.cToken); uint ethPrice = openOracleView.getUnderlyingPrice(ethConfig.cToken); require(ethPrice != 0, "eth price 0"); return mul(tokenPrice, 1e18) / ethPrice; } function assetPrices(address asset) public view override returns (uint256) { return getPrices(asset); } /// @dev Overflow proof multiplication function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "multiplication overflow"); return c; } }
Fetches the current token/usd price from uniswap, with 6 decimals of precision. conversionFactor 1e18 if seeking the ETH price, and a 6 decimal ETH-USDC price in the case of other assets/ This should be impossible, but better safe than sorry Calculate uniswap time-weighted average price Underflow is a property of the accumulators: https:uniswap.org/audit.htmlorgc9b3190 Adjust rawUniswapPrice according to the units of the non-ETH asset In the case of ETH, we would have to scale by 1e6 / USDC_UNITS, but since baseUnit2 is 1e6 (USDC), it cancels unscaledPriceMantissa ethBaseUnit / config.baseUnit / expScale, but we simplify bc ethBaseUnit == expScale
function fetchAnchorPrice(string memory symbol, TokenConfig memory config, uint conversionFactor) internal virtual returns (uint) { (uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config); require(block.timestamp > oldTimestamp, "now must come after before"); uint timeElapsed = block.timestamp - oldTimestamp; FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)); uint rawUniswapPriceMantissa = priceAverage.decode112with18(); uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, conversionFactor); uint anchorPrice; if (config.isUniswapReversed) { anchorPrice = unscaledPriceMantissa / config.baseUnit; anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale; } emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp); return anchorPrice; }
2,223,595
//Address: 0x5f391f8253475bffa27b2f8544994f9717ab310d //Contract name: CromIco //Balance: 0.94901046 Ether //Verification Date: 11/16/2017 //Transacion Count: 27 // CODE STARTS HERE pragma solidity ^0.4.15; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ClaimableTokens is Ownable { address public claimedTokensWallet; function ClaimableTokens(address targetWallet) { claimedTokensWallet = targetWallet; } function claimTokens(address tokenAddress) public onlyOwner { require(tokenAddress != 0x0); ERC20 claimedToken = ERC20(tokenAddress); uint balance = claimedToken.balanceOf(this); claimedToken.transfer(claimedTokensWallet, balance); } } contract CromToken is Ownable, ERC20, ClaimableTokens { using SafeMath for uint256; string public constant name = "CROM Token"; string public constant symbol = "CROM"; uint8 public constant decimals = 0; uint256 public constant INITIAL_SUPPLY = 10 ** 7; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; function CromToken() Ownable() ClaimableTokens(msg.sender) { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = totalSupply; } function transfer(address to, uint256 value) public returns (bool success) { require(to != 0x0); require(balances[msg.sender] >= value); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, 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; } function allowance(address owner, address spender) public constant returns (uint256 remaining) { return allowed[owner][spender]; } function balanceOf(address who) public constant returns (uint256) { return balances[who]; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(to != 0x0); require(balances[from] >= value); require(value <= allowed[from][msg.sender]); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); Transfer(from, to, value); return true; } } contract CromIco is Ownable, ClaimableTokens { using SafeMath for uint256; CromToken public token; // start and end timestamps where investments are allowed (both inclusive) uint public preStartTime; uint public startTime; uint public endTime; // address where funds are collected address public targetWallet; bool public targetWalletVerified; // caps definitions uint256 public constant SOFT_CAP = 8000 ether; uint256 public constant HARD_CAP = 56000 ether; // token price uint256 public constant TOKEN_PRICE = 10 finney; uint public constant BONUS_BATCH = 2 * 10 ** 6; uint public constant BONUS_PERCENTAGE = 25; uint256 public constant MINIMAL_PRE_ICO_INVESTMENT = 10 ether; // ICO duration uint public constant PRE_DURATION = 14 days; uint public constant DURATION = 14 days; // contributions per individual mapping (address => uint256) public balanceOf; // wallets allowed to take part in the pre ico mapping (address => bool) public preIcoMembers; // total amount of funds raised uint256 public amountRaised; uint256 public tokensSold; bool public paused; enum Stages { WalletUnverified, BeforeIco, Payable, AfterIco } enum PayableStages { PreIco, PublicIco } event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); // Constructor function CromIco(address tokenAddress, address beneficiaryWallet) Ownable() ClaimableTokens(beneficiaryWallet) { token = CromToken(tokenAddress); preStartTime = 1510920000; startTime = preStartTime + PRE_DURATION; endTime = startTime + DURATION; targetWallet = beneficiaryWallet; targetWalletVerified = false; paused = false; } modifier atStage(Stages stage) { require(stage == getCurrentStage()); _; } // fallback function can be used to buy tokens function() payable atStage(Stages.Payable) { buyTokens(); } // low level token purchase function function buyTokens() internal { require(msg.sender != 0x0); require(msg.value > 0); require(!paused); uint256 weiAmount = msg.value; // calculate token amount to be transferred uint256 tokens = calculateTokensAmount(weiAmount); require(tokens > 0); require(token.balanceOf(this) >= tokens); if (PayableStages.PreIco == getPayableStage()) { require(preIcoMembers[msg.sender]); require(weiAmount.add(balanceOf[msg.sender]) >= MINIMAL_PRE_ICO_INVESTMENT); require(tokensSold.add(tokens) <= BONUS_BATCH); } amountRaised = amountRaised.add(weiAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(weiAmount); tokensSold = tokensSold.add(tokens); token.transfer(msg.sender, tokens); TokenPurchase(msg.sender, weiAmount, tokens); } function verifyTargetWallet() public atStage(Stages.WalletUnverified) { require(msg.sender == targetWallet); targetWalletVerified = true; } // add a list of wallets to be allowed to take part in pre ico function addPreIcoMembers(address[] members) public onlyOwner { for (uint i = 0; i < members.length; i++) { preIcoMembers[members[i]] = true; } } // remove a list of wallets to be allowed to take part in pre ico function removePreIcoMembers(address[] members) public onlyOwner { for (uint i = 0; i < members.length; i++) { preIcoMembers[members[i]] = false; } } // @return true if the ICO is in pre ICO phase function isPreIcoActive() public constant returns (bool) { bool isPayable = Stages.Payable == getCurrentStage(); bool isPreIco = PayableStages.PreIco == getPayableStage(); return isPayable && isPreIco; } // @return true if the public ICO is in progress function isPublicIcoActive() public constant returns (bool) { bool isPayable = Stages.Payable == getCurrentStage(); bool isPublic = PayableStages.PublicIco == getPayableStage(); return isPayable && isPublic; } // @return true if ICO has ended function hasEnded() public constant returns (bool) { return Stages.AfterIco == getCurrentStage(); } // @return true if the soft cap has been reached function softCapReached() public constant returns (bool) { return amountRaised >= SOFT_CAP; } // withdraw the contributed funds if the ICO has // ended and the goal has not been reached function withdrawFunds() public atStage(Stages.AfterIco) returns(bool) { require(!softCapReached()); require(balanceOf[msg.sender] > 0); uint256 balance = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; msg.sender.transfer(balance); return true; } // transfer the raised funds to the target wallet if // the ICO is over and the goal has been reached function finalizeIco() public onlyOwner atStage(Stages.AfterIco) { require(softCapReached()); targetWallet.transfer(this.balance); } function withdrawUnsoldTokens() public onlyOwner atStage(Stages.AfterIco) { token.transfer(targetWallet, token.balanceOf(this)); } function pause() public onlyOwner { require(!paused); paused = true; } function resume() public onlyOwner { require(paused); paused = false; } function changeTargetWallet(address wallet) public onlyOwner { targetWallet = wallet; targetWalletVerified = false; } function calculateTokensAmount(uint256 funds) internal returns (uint256) { uint256 tokens = funds.div(TOKEN_PRICE); if (tokensSold < BONUS_BATCH) { if (tokensSold.add(tokens) > BONUS_BATCH) { uint256 bonusBaseTokens = BONUS_BATCH.mul(100).div(125).sub(tokensSold); tokens = tokens.add(bonusBaseTokens.mul(BONUS_PERCENTAGE).div(100)); } else { tokens = tokens.mul(BONUS_PERCENTAGE + 100).div(100); } } return tokens; } function getCurrentStage() internal constant returns (Stages) { if (!targetWalletVerified) { return Stages.WalletUnverified; } else if (now < preStartTime) { return Stages.BeforeIco; } else if (now < endTime && amountRaised < HARD_CAP) { return Stages.Payable; } else { return Stages.AfterIco; } } function getPayableStage() internal constant returns (PayableStages) { if (now < startTime) { return PayableStages.PreIco; } else { return PayableStages.PublicIco; } } }
fallback function can be used to buy tokens
function() payable atStage(Stages.Payable) { buyTokens(); }
1,031,410
/** *Submitted for verification at Etherscan.io on 2021-08-05 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: ICurveFi interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // stETH pool uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external payable; function balances(int128) external view returns (uint256); function get_dy( int128 from, int128 to, uint256 _from_amount ) external view returns (uint256); function calc_token_amount( uint256[2] calldata amounts, bool is_deposit) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/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: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: iearn-finance/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: ISteth interface ISteth is IERC20 { event Submitted(address sender, uint256 amount, address referral); function submit(address) external payable returns (uint256); } // Part: IWETH interface IWETH is IERC20 { function deposit() external payable; function decimals() external view returns (uint256); function withdraw(uint256) external; } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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"); } } } // Part: iearn-finance/[email protected]/VaultAPI 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 pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() 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); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @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.4.3"; } /** * @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 onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { 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" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!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. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a 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; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @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 conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @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`). * * `_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. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @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 * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) 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. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); 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 * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * 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/main/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 callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); 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 onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } 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. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } 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 the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); 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 onlyEmergencyAuthorized { 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 onlyGovernance { 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))); } } // File: Strategy.sol // Import interfaces for many popular DeFi projects, or add your own! //import "../interfaces/<protocol>/<Interface>.sol"; contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; bool public checkLiqGauge = true; ICurveFi public constant StableSwapSTETH = ICurveFi(0xDC24316b9AE028F1497c275EB9192a3Ea0f67022); IWETH public constant weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); ISteth public constant stETH = ISteth(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84); address private referal = 0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7; //stratms. for recycling and redepositing uint256 public maxSingleTrade; uint256 public constant DENOMINATOR = 10_000; uint256 public slippageProtectionOut;// = 50; //out of 10000. 50 = 0.5% int128 private constant WETHID = 0; int128 private constant STETHID = 1; constructor(address _vault) public BaseStrategy(_vault) { // You can set these parameters on deployment to whatever you want maxReportDelay = 43200; profitFactor = 2000; debtThreshold = 400*1e18; stETH.approve(address(StableSwapSTETH), type(uint256).max); maxSingleTrade = 1_000 * 1e18; slippageProtectionOut = 50; } //we get eth receive() external payable {} function updateReferal(address _referal) public onlyEmergencyAuthorized { referal = _referal; } function updateMaxSingleTrade(uint256 _maxSingleTrade) public onlyVaultManagers { maxSingleTrade = _maxSingleTrade; } function updateSlippageProtectionOut(uint256 _slippageProtectionOut) public onlyVaultManagers { slippageProtectionOut = _slippageProtectionOut; } function invest(uint256 _amount) external onlyEmergencyAuthorized{ require(wantBalance() >= _amount); uint256 realInvest = Math.min(maxSingleTrade, _amount); _invest(realInvest); } //should never have stuck eth but just incase function rescueStuckEth() external onlyEmergencyAuthorized{ weth.deposit{value: address(this).balance}(); } function name() external override view returns (string memory) { // Add your own name here, suggestion e.g. "StrategyCreamYFI" return "StrategystETHAccumulator"; } // We are purposely treating stETH and ETH as being equivalent. // This is for a few reasons. The main one is that we do not have a good way to value stETH at any current time without creating exploit routes. // Currently you can mint eth for steth but can't burn steth for eth so need to sell. Once eth 2.0 is merged you will be able to burn 1-1 as well. // The main downside here is that we will noramlly overvalue our position as we expect stETH to trade slightly below peg. // That means we will earn profit on deposits and take losses on withdrawals. // This may sound scary but it is the equivalent of using virtualprice in a curve lp. As we have seen from many exploits, virtual pricing is safer than touch pricing. function estimatedTotalAssets() public override view returns (uint256) { return stethBalance().add(wantBalance()); } function wantBalance() public view returns (uint256){ return want.balanceOf(address(this)); } function stethBalance() public view returns (uint256){ return stETH.balanceOf(address(this)); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 wantBal = wantBalance(); uint256 stethBal = stethBalance(); uint256 totalAssets = wantBal.add(stethBal); uint256 debt = vault.strategies(address(this)).totalDebt; if(totalAssets >= debt){ _profit = totalAssets.sub(debt); uint256 toWithdraw = _profit.add(_debtOutstanding); if(toWithdraw > wantBal){ uint256 willWithdraw = Math.min(maxSingleTrade, toWithdraw); uint256 withdrawn = _divest(willWithdraw); //we step our withdrawals. adjust max single trade to withdraw more if(withdrawn < willWithdraw){ _loss = willWithdraw.sub(withdrawn); } } wantBal = wantBalance(); //net off profit and loss if(_profit >= _loss){ _profit = _profit - _loss; _loss = 0; }else{ _profit = 0; _loss = _loss - _profit; } //profit + _debtOutstanding must be <= wantbalance. Prioritise profit first if(wantBal < _profit){ _profit = wantBal; }else if(wantBal < toWithdraw){ _debtPayment = wantBal.sub(_profit); }else{ _debtPayment = _debtOutstanding; } }else{ _loss = debt.sub(totalAssets); } } function ethToWant(uint256 _amtInWei) public view override returns (uint256){ return _amtInWei; } function liquidateAllPositions() internal override returns (uint256 _amountFreed){ _divest(stethBalance()); _amountFreed = wantBalance(); } function adjustPosition(uint256 _debtOutstanding) internal override { uint256 toInvest = wantBalance(); if(toInvest > 0){ uint256 realInvest = Math.min(maxSingleTrade, toInvest); _invest(realInvest); } } function _invest(uint256 _amount) internal returns (uint256){ uint256 before = stethBalance(); weth.withdraw(_amount); //test if we should buy instead of mint uint256 out = StableSwapSTETH.get_dy(WETHID, STETHID, _amount); if(out < _amount){ stETH.submit{value: _amount}(referal); }else{ StableSwapSTETH.exchange{value: _amount}(WETHID, STETHID, _amount, _amount); } return stethBalance().sub(before); } function _divest(uint256 _amount) internal returns (uint256){ uint256 before = wantBalance(); uint256 slippageAllowance = _amount.mul(DENOMINATOR.sub(slippageProtectionOut)).div(DENOMINATOR); StableSwapSTETH.exchange(STETHID, WETHID, _amount,slippageAllowance); weth.deposit{value: address(this).balance}(); return wantBalance().sub(before); } // we attempt to withdraw the full amount and let the user decide if they take the loss or not function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 wantBal = wantBalance(); if(wantBal < _amountNeeded){ uint256 toWithdraw = _amountNeeded.sub(wantBal); uint256 withdrawn = _divest(toWithdraw); if(withdrawn < toWithdraw){ _loss = toWithdraw.sub(withdrawn); } } _liquidatedAmount = _amountNeeded.sub(_loss); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { uint256 stethBal = stethBalance(); if (stethBal > 0) { stETH.transfer(_newStrategy, stethBal); } } // 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 override view returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = address(stETH); return protected; } }
should never have stuck eth but just incase
function rescueStuckEth() external onlyEmergencyAuthorized{ }
7,789,640
./partial_match/4/0xc608bA9b7d5Be5A93A8eB181b99197c6600781Cf/sources/Dgate.sol
accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } }
8,600,938
./full_match/7700/0x6eA48824253f64662945Ae77A790331D7183f8c0/sources/project_/contracts/eip/2981/ERC2981Collection.sol
This sets the contract as royalty reciever (useful with abstract PaymentSplitter) permille: Percentage you want so 3.5% -> 35
function setRoyaltiesThis( uint16 permille ) external virtual override onlyOwner() { _setRoyalties(address(this), permille); }
4,661,717
./full_match/11155111/0x88aec82f14002a56014819f4e23a22eB32F528b1/sources/contracts/staking/Staking.sol
Set the rebate parameters. _alphaNumerator Numerator of `alpha` in the rebates function _alphaDenominator Denominator of `alpha` in the rebates function _lambdaNumerator Numerator of `lambda` in the rebates function _lambdaDenominator Denominator of `lambda` in the rebates function/
function setRebateParameters( uint32 _alphaNumerator, uint32 _alphaDenominator, uint32 _lambdaNumerator, uint32 _lambdaDenominator ) external override onlyGovernor { _setRebateParameters( _alphaNumerator, _alphaDenominator, _lambdaNumerator, _lambdaDenominator ); }
3,838,745
pragma solidity ^0.5.8; /** This scd to mcd migration works without pool. ETH free(scd) => lock(mcd) ==> dai draw(mcd) => swap(dai=>sai) => wipe(scd) */ interface TubInterface { function open() external returns (bytes32); function join(uint) external; function exit(uint) external; function lock(bytes32, uint) external; function free(bytes32, uint) external; function draw(bytes32, uint) external; function wipe(bytes32, uint) external; function give(bytes32, address) external; function shut(bytes32) external; function cups(bytes32) external view returns (address, uint, uint, uint); function gem() external view returns (TokenInterface); function gov() external view returns (TokenInterface); function skr() external view returns (TokenInterface); function sai() external view returns (TokenInterface); function ink(bytes32) external view returns (uint); function tab(bytes32) external returns (uint); function rap(bytes32) external returns (uint); function per() external view returns (uint); function pep() external view returns (PepInterface); } interface TokenInterface { function allowance(address, address) external view returns (uint); function balanceOf(address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function deposit() external payable; function withdraw(uint) external; } interface PepInterface { function peek() external returns (bytes32, bool); } interface UniswapExchange { function getEthToTokenOutputPrice(uint256 tokensBought) external view returns (uint256 ethSold); function getTokenToEthOutputPrice(uint256 ethBought) external view returns (uint256 tokensSold); function tokenToTokenSwapOutput( uint256 tokensBought, uint256 maxTokensSold, uint256 maxEthSold, uint256 deadline, address tokenAddr ) external returns (uint256 tokensSold); function ethToTokenSwapOutput(uint256 tokensBought, uint256 deadline) external payable returns (uint256 ethSold); } interface UniswapFactoryInterface { function getExchange(address token) external view returns (address exchange); } interface MCDInterface { function swapDaiToSai(uint wad) external; function migrate(bytes32 cup) external returns (uint cdp); } interface PoolInterface { function accessToken(address[] calldata ctknAddr, uint[] calldata tknAmt, bool isCompound) external; function paybackToken(address[] calldata ctknAddr, bool isCompound) external payable; } interface OtcInterface { function getPayAmount(address, address, uint) external view returns (uint); function buyAllAmount( address, uint, address, uint ) external; } interface GemLike { function approve(address, uint) external; function transfer(address, uint) external; function transferFrom(address, address, uint) external; function deposit() external payable; function withdraw(uint) external; } interface JugLike { function drip(bytes32) external returns (uint); } interface ManagerLike { function cdpCan(address, uint, address) external view returns (uint); function ilks(uint) external view returns (bytes32); function owns(uint) external view returns (address); function urns(uint) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint); function give(uint, address) external; function cdpAllow(uint, address, uint) external; function urnAllow(address, uint) external; function frob(uint, int, int) external; function flux(uint, address, uint) external; function move(uint, address, uint) external; function exit( address, uint, address, uint ) external; function quit(uint, address) external; function enter(address, uint) external; function shift(uint, uint) external; } interface VatLike { function can(address, address) external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function dai(address) external view returns (uint); function urns(bytes32, address) external view returns (uint, uint); function frob( bytes32, address, address, address, int, int ) external; function hope(address) external; function move(address, address, uint) external; } interface GemJoinLike { function dec() external returns (uint); function gem() external returns (GemLike); function join(address, uint) external payable; function exit(address, uint) external; } interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint) external payable; function exit(address, uint) external; } /** Swap Functionality */ interface ScdMcdMigration { function swapDaiToSai(uint daiAmt) external; function swapSaiToDai(uint saiAmt) external; } interface InstaMcdAddress { function manager() external returns (address); function dai() external returns (address); function daiJoin() external returns (address); function jug() external returns (address); function gov() external returns (address); function ethAJoin() external returns (address); function saiJoin() external returns (address); function migration() external returns (address payable); } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "math-not-safe"); } function sub(uint x, uint y) internal pure returns (uint z) { z = x - y <= x ? x - y : 0; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "math-not-safe"); } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } } contract Helpers is DSMath { /** * @dev get MakerDAO SCD CDP engine */ function getSaiTubAddress() public pure returns (address sai) { sai = 0x448a5065aeBB8E423F0896E6c5D525C040f59af3; } /** * @dev get MakerDAO MCD Address contract */ function getMcdAddresses() public pure returns (address mcd) { mcd = 0xF23196DF1C440345DE07feFbe556a5eF0dcD29F0; } /** * @dev get ETH Address */ function getETHAddress() public pure returns (address ethAddr) { ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // main } /** * @dev get Sai (Dai v1) address */ function getSaiAddress() public pure returns (address sai) { sai = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359; } /** * @dev get Dai (Dai v2) address */ function getDaiAddress() public pure returns (address dai) { dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; } /** * @dev get Compound WETH Address */ function getWETHAddress() public pure returns (address wethAddr) { wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // main } /** * @dev get OTC Address */ function getOtcAddress() public pure returns (address otcAddr) { otcAddr = 0x39755357759cE0d7f32dC8dC45414CCa409AE24e; // main } /** * @dev get InstaDApp CDP's Address */ function getGiveAddress() public pure returns (address addr) { addr = 0xc679857761beE860f5Ec4B3368dFE9752580B096; } /** * @dev get uniswap MKR exchange */ function getUniswapMKRExchange() public pure returns (address ume) { ume = 0x2C4Bd064b998838076fa341A83d007FC2FA50957; } /** * @dev get uniswap MKR exchange */ function getUniFactoryAddr() public pure returns (address ufa) { ufa = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; } /** * @dev setting allowance if required */ function setApproval(address erc20, uint srcAmt, address to) internal { TokenInterface erc20Contract = TokenInterface(erc20); uint tokenAllowance = erc20Contract.allowance(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.approve(to, uint(-1)); } } } contract MKRSwapper is Helpers { function getBestMkrSwap(address srcTknAddr, uint destMkrAmt) public view returns(uint bestEx, uint srcAmt) { if (srcTknAddr == getDaiAddress()) { //Check samyak - oasis was failing. srcAmt = getUniswapSwap(srcTknAddr, destMkrAmt); bestEx = 1; } else { uint oasisPrice = getOasisSwap(srcTknAddr, destMkrAmt); uint uniswapPrice = getUniswapSwap(srcTknAddr, destMkrAmt); require(oasisPrice != 0 && uniswapPrice != 0, "swap price 0"); srcAmt = oasisPrice < uniswapPrice ? oasisPrice : uniswapPrice; bestEx = oasisPrice < uniswapPrice ? 0 : 1; // if 0 then use Oasis for Swap, if 1 then use Uniswap } } function getOasisSwap(address tokenAddr, uint destMkrAmt) public view returns(uint srcAmt) { TokenInterface mkr = TubInterface(getSaiTubAddress()).gov(); address srcTknAddr = tokenAddr == getETHAddress() ? getWETHAddress() : tokenAddr; srcAmt = OtcInterface(getOtcAddress()).getPayAmount(srcTknAddr, address(mkr), destMkrAmt); } function getUniswapSwap(address srcTknAddr, uint destMkrAmt) public view returns(uint srcAmt) { UniswapExchange mkrEx = UniswapExchange(getUniswapMKRExchange()); if (srcTknAddr == getETHAddress()) { srcAmt = mkrEx.getEthToTokenOutputPrice(destMkrAmt); } else { address buyTknExAddr = UniswapFactoryInterface(getUniFactoryAddr()).getExchange(srcTknAddr); UniswapExchange buyTknEx = UniswapExchange(buyTknExAddr); srcAmt = buyTknEx.getTokenToEthOutputPrice(mkrEx.getEthToTokenOutputPrice(destMkrAmt)); //Check thrilok is this correct } } function swapToMkr(address tokenAddr, uint govFee) internal { (uint bestEx, uint srcAmt) = getBestMkrSwap(tokenAddr, govFee); if (bestEx == 0) { swapToMkrOtc(tokenAddr, srcAmt, govFee); } else { swapToMkrUniswap(tokenAddr, srcAmt, govFee); } } function swapToMkrOtc(address tokenAddr, uint srcAmt, uint govFee) internal { address mkr = InstaMcdAddress(getMcdAddresses()).gov(); address srcTknAddr = tokenAddr == getETHAddress() ? getWETHAddress() : tokenAddr; if (srcTknAddr == getWETHAddress()) { TokenInterface weth = TokenInterface(getWETHAddress()); weth.deposit.value(srcAmt)(); } else if (srcTknAddr != getSaiAddress() && srcTknAddr != getDaiAddress()) { require(TokenInterface(srcTknAddr).transferFrom(msg.sender, address(this), srcAmt), "Tranfer-failed"); } setApproval(srcTknAddr, srcAmt, getOtcAddress()); OtcInterface(getOtcAddress()).buyAllAmount( mkr, govFee, srcTknAddr, srcAmt ); } function swapToMkrUniswap(address tokenAddr, uint srcAmt, uint govFee) internal { UniswapExchange mkrEx = UniswapExchange(getUniswapMKRExchange()); address mkr = InstaMcdAddress(getMcdAddresses()).gov(); if (tokenAddr == getETHAddress()) { mkrEx.ethToTokenSwapOutput.value(srcAmt)(govFee, uint(1899063809)); } else { if (tokenAddr != getSaiAddress() && tokenAddr != getDaiAddress()) { require(TokenInterface(tokenAddr).transferFrom(msg.sender, address(this), srcAmt), "not-approved-yet"); } address buyTknExAddr = UniswapFactoryInterface(getUniFactoryAddr()).getExchange(tokenAddr); UniswapExchange buyTknEx = UniswapExchange(buyTknExAddr); setApproval(tokenAddr, srcAmt, buyTknExAddr); buyTknEx.tokenToTokenSwapOutput( govFee, srcAmt, uint(999000000000000000000), uint(1899063809), // 6th March 2030 GMT // no logic mkr ); } } } contract SCDResolver is MKRSwapper { function getFeeOfCdp(bytes32 cup, uint _wad) internal returns (uint mkrFee) { TubInterface tub = TubInterface(getSaiTubAddress()); (bytes32 val, bool ok) = tub.pep().peek(); if (ok && val != 0) { // MKR required for wipe = Stability fees accrued in Dai / MKRUSD value mkrFee = rdiv(tub.rap(cup), tub.tab(cup)); mkrFee = rmul(_wad, mkrFee); mkrFee = wdiv(mkrFee, uint(val)); } } function open() internal returns (bytes32 cup) { cup = TubInterface(getSaiTubAddress()).open(); } function wipeSai(bytes32 cup, uint _wad, address payFeeWith) internal { if (_wad > 0) { TubInterface tub = TubInterface(getSaiTubAddress()); TokenInterface dai = tub.sai(); TokenInterface mkr = tub.gov(); (address lad,,,) = tub.cups(cup); require(lad == address(this), "cup-not-owned"); setAllowance(dai, getSaiTubAddress()); setAllowance(mkr, getSaiTubAddress()); uint mkrFee = getFeeOfCdp(cup, _wad); if (payFeeWith != address(mkr) && mkrFee > 0) { swapToMkr(payFeeWith, mkrFee); //otc or uniswap } else if (payFeeWith == address(mkr) && mkrFee > 0) { require(TokenInterface(address(mkr)).transferFrom(msg.sender, address(this), mkrFee), "Tranfer-failed"); } tub.wipe(cup, _wad); } } function scdFree(bytes32 cup, uint jam) internal { if (jam > 0) { address tubAddr = getSaiTubAddress(); TubInterface tub = TubInterface(tubAddr); TokenInterface peth = tub.skr(); uint ink = rdiv(jam, tub.per()); ink = rmul(ink, tub.per()) <= jam ? ink : ink - 1; tub.free(cup, ink); setAllowance(peth, tubAddr); tub.exit(ink); } } function setAllowance(TokenInterface _token, address _spender) private { if (_token.allowance(address(this), _spender) != uint(-1)) { _token.approve(_spender, uint(-1)); } } } contract MCDResolver is SCDResolver { function openVault() public returns (uint cdp) { address manager = InstaMcdAddress(getMcdAddresses()).manager(); bytes32 ilk = 0x4554482d41000000000000000000000000000000000000000000000000000000; cdp = ManagerLike(manager).open(ilk, address(this)); } function mcdLock( uint cdp, uint ink ) internal { address manager = InstaMcdAddress(getMcdAddresses()).manager(); address ethJoin = InstaMcdAddress(getMcdAddresses()).ethAJoin(); GemJoinLike(ethJoin).gem().approve(address(ethJoin), ink); GemJoinLike(ethJoin).join(address(this), ink); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), int(ink), 0 ); } function daiDraw( uint cdp, uint wad ) internal { address manager = InstaMcdAddress(getMcdAddresses()).manager(); address jug = InstaMcdAddress(getMcdAddresses()).jug(); address daiJoin = InstaMcdAddress(getMcdAddresses()).daiJoin(); address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Updates stability fee rate before generating new debt uint rate = JugLike(jug).drip(ilk); // Check Thrilok - check if its working int dart; // Gets actual rate from the vat // (, uint rate,,,) = VatLike(vat).ilks(ilk); // Check Thrilok - check if above its working // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = int(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } ManagerLike(manager).frob(cdp, 0, dart); // Moves the DAI amount (balance in the vat in rad) to proxy's address ManagerLike(manager).move(cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } DaiJoinLike(daiJoin).exit(address(this), wad); } function getDaiDebt(uint cdp) internal returns (uint debt) { address manager = InstaMcdAddress(getMcdAddresses()).manager(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = 0x4554482d41000000000000000000000000000000000000000000000000000000; (, uint art) = VatLike(ManagerLike(manager).vat()).urns(ilk, urn); (,uint rate,,,) = VatLike(ManagerLike(manager).vat()).ilks(ilk); debt = rmul(art, rate); } } contract MigrateHelper is MCDResolver { function swapDaiToSai(uint wad) internal { address scdMcdMigration = InstaMcdAddress(getMcdAddresses()).migration(); // Migration contract address TokenInterface dai = TokenInterface(getDaiAddress()); if (dai.allowance(address(this), scdMcdMigration) < wad) { dai.approve(scdMcdMigration, wad); } ScdMcdMigration(scdMcdMigration).swapDaiToSai(wad); } function setSplitAmount( bytes32 cup, uint toConvert, address payFeeWith ) internal returns (uint _wad, uint _ink, uint maxConvert) { // Set ratio according to user. TubInterface tub = TubInterface(getSaiTubAddress()); maxConvert = toConvert; uint saiBal = tub.sai().balanceOf(InstaMcdAddress(getMcdAddresses()).saiJoin()); uint _wadTotal = tub.tab(cup); // wad according to toConvert ratio _wad = wmul(_wadTotal, toConvert); // if migration is by debt method, Add fee(SAI) to _wad if (payFeeWith == getDaiAddress() || payFeeWith == getSaiAddress()) { //Check samyak (,uint feeAmt) = getBestMkrSwap(payFeeWith, getFeeOfCdp(cup, _wad)); if (saiBal < add(_wad, feeAmt)) { (, uint totalFeeAmt) = getBestMkrSwap(payFeeWith, getFeeOfCdp(cup, _wadTotal)); uint _totalWadDebt = add(_wadTotal, totalFeeAmt); maxConvert = sub(wdiv(saiBal, _totalWadDebt), 1000); // (saiBal / debt + fee) => toConvert _wad = wmul(_wadTotal, maxConvert); } } if (saiBal < _wad) { // set saiBal as wad amount And sub feeAmt(feeAmt > 0, when its debt method). _wad = sub(saiBal, 100000); // set new convert ratio according to sai_join balance. maxConvert = sub(wdiv(saiBal, _wadTotal), 100); } // ink according to maxConvert ratio. _ink = wmul(tub.ink(cup), maxConvert); } function ethScdToMcd(bytes32 scdCup, uint mcdCup, uint _ink) internal { //transfer assets from scdCup to mcdCup. scdFree(scdCup, _ink); mcdLock(mcdCup, _ink); } function drawDaiAndPaySai( bytes32 scdCup, uint mcdCup, uint _wad, address payFeeWith ) internal { uint _wadForDebt = _wad; if (payFeeWith == getDaiAddress() || payFeeWith == getSaiAddress()) { (,uint tknAmt) = getBestMkrSwap(payFeeWith, getFeeOfCdp(scdCup, _wad)); _wadForDebt = add(_wadForDebt, tknAmt); } daiDraw(mcdCup, _wadForDebt); swapDaiToSai((payFeeWith == getSaiAddress() ? _wadForDebt :_wad)); wipeSai(scdCup, _wad, payFeeWith); } } contract MigrateResolver is MigrateHelper { event LogScdToMcdMigrate(uint scdCdp, uint toConvert, uint coll, uint debt, address payFeeWith, uint mcdCdp, uint newMcdCdp); function migrate( uint scdCDP, uint mergeCDP, uint toConvert, address payFeeWith ) external payable { uint mcdCdp = mergeCDP == 0 ? openVault() : mergeCDP; bytes32 scdCup = bytes32(scdCDP); uint maxConvert = toConvert; uint _wad; uint _ink; (_wad, _ink, maxConvert) = setSplitAmount(scdCup, toConvert, payFeeWith); require(add(getDaiDebt(mcdCdp), _wad) >= 20*(10**18), "Min 20 Dai required to migrate."); ethScdToMcd(scdCup, mcdCdp, _ink); drawDaiAndPaySai( scdCup, mcdCdp, _wad, payFeeWith ); //Transfer if any ETH leftover. if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } emit LogScdToMcdMigrate( uint(scdCup), maxConvert, _ink, _wad, payFeeWith, mergeCDP, mcdCdp ); } } contract InstaMcdMigrate is MigrateResolver { function() external payable {} }
Set ratio according to user. wad according to toConvert ratio if migration is by debt method, Add fee(SAI) to _wad
function setSplitAmount( bytes32 cup, uint toConvert, address payFeeWith ) internal returns (uint _wad, uint _ink, uint maxConvert) { TubInterface tub = TubInterface(getSaiTubAddress()); maxConvert = toConvert; uint saiBal = tub.sai().balanceOf(InstaMcdAddress(getMcdAddresses()).saiJoin()); uint _wadTotal = tub.tab(cup); _wad = wmul(_wadTotal, toConvert); (,uint feeAmt) = getBestMkrSwap(payFeeWith, getFeeOfCdp(cup, _wad)); if (saiBal < add(_wad, feeAmt)) { (, uint totalFeeAmt) = getBestMkrSwap(payFeeWith, getFeeOfCdp(cup, _wadTotal)); uint _totalWadDebt = add(_wadTotal, totalFeeAmt); _wad = wmul(_wadTotal, maxConvert); } }
13,132,216
./full_match/80001/0x0df0d5070db1B12421d3EbD926Ce54f287919720/sources/src/MintpadERC1155Evolve.sol
Collects and distributes the primary sale value of NFTs being claimed.
function collectPriceOnClaim( uint256 _tokenId, address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal virtual override { if (_pricePerToken == 0) { return; } uint256 totalPrice = _quantityToClaim * _pricePerToken; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == totalPrice + transactionFee, "Must send total price."); } CurrencyTransferLib.transferCurrency(_currency, msg.sender, platformAddress, transactionFee); CurrencyTransferLib.transferCurrency(_currency, msg.sender, _primarySaleRecipient, totalPrice); }
5,594,451
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IStaking.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract BondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond address public immutable bondCalculator; // calculates value of LP tokens bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference time for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt uint32 vestingTerm; // in seconds } // Info for bond holder struct Bond { uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in seconds) between adjustments uint32 lastTime; // timestamp when last adjustment made } constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) KEEPER */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( KEEPER ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 ); } } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 () { 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IBondCalculator { function markdown( address _LP ) external view returns ( uint ); function valuation( address pair_, uint amount_ ) external view returns ( uint _value ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IStaking { function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ); function claim ( address _recipient ) external returns ( uint ); function forfeit() external returns ( uint ); function toggleLock() external; function unstake( uint _amount, bool _trigger ) external returns ( uint ); function rebase() external; function index() external view returns ( uint ); function contractBalance() external view returns ( uint ); function totalStaked() external view returns ( uint ); function supplyInWarmup() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ITreasury { function deposit( uint _amount, address _token, uint _profit ) external returns ( uint ); function withdraw( uint _amount, address _token ) external; function valueOfToken( address _token, uint _amount ) external view returns ( uint value_ ); function mint( address _recipient, uint _amount ) external; function mintRewards( address _recipient, uint _amount ) external; function incurDebt( uint amount_, address token_ ) external; function repayDebtWithReserve( uint amount_, address token_ ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0 <0.8.0; import "./FullMath.sol"; library Babylonian { function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; library SafeMathExtended { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function add32(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(a, b, "SafeMath: subtraction overflow"); } function sub32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // 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.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: AGPL-3.0-or-later pragma solidity >=0.5.0 <0.8.0; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VLPBondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable bondCalculator; // calculates value of LP tokens AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint gonsPayout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; require( _bondCalculator != address(0) ); bondCalculator = _bondCalculator; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice() .mul( IBondCalculator( bondCalculator ).markdown( principle ) ) .mul( uint( assetPrice() ) ) .div( 1e12 ); } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; 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: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IsKEEPER is IERC20 { function rebase( uint256 profit_, uint epoch_) external returns (uint256); function circulatingSupply() external view returns (uint256); function balanceOf(address who) external override view returns (uint256); function gonsForBalance( uint amount ) external view returns ( uint ); function balanceForGons( uint gons ) external view returns ( uint ); function index() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IwTROVE is IERC20 { function wrap(uint _amount) external returns (uint); function unwrap(uint _amount) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VLPBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable bondCalculator; // calculates value of LP tokens AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; require( _bondCalculator != address(0) ); bondCalculator = _bondCalculator; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice() .mul( IBondCalculator( bondCalculator ).markdown( principle ) ) .mul( uint( assetPrice() ) ) .div( 1e12 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/SafeMathExtended.sol"; contract StakingDistributor is Ownable { using SafeERC20 for IERC20; using SafeMathExtended for uint256; using SafeMathExtended for uint32; IERC20 immutable KEEPER; ITreasury immutable treasury; uint32 public immutable epochLength; uint32 public nextEpochTime; mapping( uint => Adjust ) public adjustments; /* ====== STRUCTS ====== */ struct Info { uint rate; // in ten-thousandths ( 5000 = 0.5% ) address recipient; } Info[] public info; struct Adjust { bool add; uint rate; uint target; } constructor( address _treasury, address _KEEPER, uint32 _epochLength, uint32 _nextEpochTime ) { require( _treasury != address(0) ); treasury = ITreasury( _treasury ); require( _KEEPER != address(0) ); KEEPER = IERC20( _KEEPER ); epochLength = _epochLength; nextEpochTime = _nextEpochTime; } /** @notice send epoch reward to staking contract */ function distribute() external returns (bool) { if ( nextEpochTime <= uint32(block.timestamp) ) { nextEpochTime = nextEpochTime.add32( epochLength ); // set next epoch block // distribute rewards to each recipient for ( uint i = 0; i < info.length; i++ ) { if ( info[ i ].rate > 0 ) { treasury.mintRewards( // mint and send from treasury info[ i ].recipient, nextRewardAt( info[ i ].rate ) ); adjust( i ); // check for adjustment } } return true; } else { return false; } } /** @notice increment reward rate for collector */ function adjust( uint _index ) internal { Adjust memory adjustment = adjustments[ _index ]; if ( adjustment.rate != 0 ) { if ( adjustment.add ) { // if rate should increase info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate if ( info[ _index ].rate >= adjustment.target ) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } else { // if rate should decrease info[ _index ].rate = info[ _index ].rate.sub( adjustment.rate ); // lower rate if ( info[ _index ].rate <= adjustment.target || info[ _index ].rate < adjustment.rate) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } } } /* ====== VIEW FUNCTIONS ====== */ /** @notice view function for next reward at given rate @param _rate uint @return uint */ function nextRewardAt( uint _rate ) public view returns ( uint ) { return KEEPER.totalSupply().mul( _rate ).div( 1000000 ); } /** @notice view function for next reward for specified address @param _recipient address @return uint */ function nextRewardFor( address _recipient ) public view returns ( uint ) { uint reward; for ( uint i = 0; i < info.length; i++ ) { if ( info[ i ].recipient == _recipient ) { reward = nextRewardAt( info[ i ].rate ); } } return reward; } /* ====== POLICY FUNCTIONS ====== */ /** @notice adds recipient for distributions @param _recipient address @param _rewardRate uint */ function addRecipient( address _recipient, uint _rewardRate ) external onlyOwner() { require( _recipient != address(0) ); info.push( Info({ recipient: _recipient, rate: _rewardRate })); } /** @notice removes recipient for distributions @param _index uint @param _recipient address */ function removeRecipient( uint _index, address _recipient ) external onlyOwner() { require( _recipient == info[ _index ].recipient ); info[ _index ] = info[info.length-1]; info.pop(); } /** @notice set adjustment info for a collector's reward rate @param _index uint @param _add bool @param _rate uint @param _target uint */ function setAdjustment( uint _index, bool _add, uint _rate, uint _target ) external onlyOwner() { require(_add || info[ _index ].rate >= _rate, "Negative adjustment rate cannot be more than current rate."); adjustments[ _index ] = Adjust({ add: _add, rate: _rate, target: _target }); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; contract oldTreasury is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event Deposit( address indexed token, uint amount, uint value ); event Withdrawal( address indexed token, uint amount, uint value ); event CreateDebt( address indexed debtor, address indexed token, uint amount, uint value ); event RepayDebt( address indexed debtor, address indexed token, uint amount, uint value ); event ReservesManaged( address indexed token, uint amount ); event ReservesUpdated( uint indexed totalReserves ); event ReservesAudited( uint indexed totalReserves ); event RewardsMinted( address indexed caller, address indexed recipient, uint amount ); event ChangeQueued( MANAGING indexed managing, address queued ); event ChangeActivated( MANAGING indexed managing, address activated, bool result ); enum MANAGING { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, DEBTOR, REWARDMANAGER, SKEEPER } IKeplerERC20 immutable KEEPER; uint public immutable secondsNeededForQueue; uint public constant keeperDecimals = 9; address[] public reserveTokens; // Push only, beware false-positives. mapping( address => bool ) public isReserveToken; mapping( address => uint ) public reserveTokenQueue; // Delays changes to mapping. address[] public reserveDepositors; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isReserveDepositor; mapping( address => uint ) public reserveDepositorQueue; // Delays changes to mapping. address[] public reserveSpenders; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isReserveSpender; mapping( address => uint ) public reserveSpenderQueue; // Delays changes to mapping. address[] public liquidityTokens; // Push only, beware false-positives. mapping( address => bool ) public isLiquidityToken; mapping( address => uint ) public LiquidityTokenQueue; // Delays changes to mapping. address[] public liquidityDepositors; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isLiquidityDepositor; mapping( address => uint ) public LiquidityDepositorQueue; // Delays changes to mapping. mapping( address => address ) public bondCalculator; // bond calculator for liquidity token address[] public reserveManagers; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isReserveManager; mapping( address => uint ) public ReserveManagerQueue; // Delays changes to mapping. address[] public liquidityManagers; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isLiquidityManager; mapping( address => uint ) public LiquidityManagerQueue; // Delays changes to mapping. address[] public debtors; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isDebtor; mapping( address => uint ) public debtorQueue; // Delays changes to mapping. mapping( address => uint ) public debtorBalance; address[] public rewardManagers; // Push only, beware false-positives. Only for viewing. mapping( address => bool ) public isRewardManager; mapping( address => uint ) public rewardManagerQueue; // Delays changes to mapping. address public sKEEPER; uint public sKEEPERQueue; // Delays change to sKEEPER address uint public totalReserves; // Risk-free value of all assets uint public totalDebt; constructor (address _KEEPER, address _USDC, address _DAI, uint _secondsNeededForQueue) { require( _KEEPER != address(0) ); KEEPER = IKeplerERC20(_KEEPER); isReserveToken[ _USDC] = true; reserveTokens.push( _USDC ); isReserveToken[ _DAI ] = true; reserveTokens.push( _DAI ); // isLiquidityToken[ _KEEPERDAI ] = true; // liquidityTokens.push( _KEEPERDAI ); secondsNeededForQueue = _secondsNeededForQueue; } /** @notice allow approved address to deposit an asset for KEEPER @param _amount uint @param _token address @param _profit uint @return send_ uint */ function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ ) { require( isReserveToken[ _token ] || isLiquidityToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); if ( isReserveToken[ _token ] ) { require( isReserveDepositor[ msg.sender ], "Not approved" ); } else { require( isLiquidityDepositor[ msg.sender ], "Not approved" ); } uint value = valueOfToken(_token, _amount); // mint KEEPER needed and store amount of rewards for distribution send_ = value.sub( _profit ); KEEPER.mint( msg.sender, send_ ); totalReserves = totalReserves.add( value ); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value ); } /** @notice allow approved address to burn KEEPER for reserves @param _amount uint @param _token address */ function withdraw( uint _amount, address _token ) external { require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions require( isReserveSpender[ msg.sender ] == true, "Not approved" ); uint value = valueOfToken( _token, _amount ); KEEPER.burnFrom( msg.sender, value ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); emit Withdrawal( _token, _amount, value ); } /** @notice allow approved address to borrow reserves @param _amount uint @param _token address */ function incurDebt( uint _amount, address _token ) external { require( isDebtor[ msg.sender ], "Not approved" ); require( isReserveToken[ _token ], "Not accepted" ); uint value = valueOfToken( _token, _amount ); uint maximumDebt = IERC20Extended( sKEEPER ).balanceOf( msg.sender ); // Can only borrow against sKEEPER held uint availableDebt = maximumDebt.sub( debtorBalance[ msg.sender ] ); require( value <= availableDebt, "Exceeds debt limit" ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].add( value ); totalDebt = totalDebt.add( value ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).transfer( msg.sender, _amount ); emit CreateDebt( msg.sender, _token, _amount, value ); } /** @notice allow approved address to repay borrowed reserves with reserves @param _amount uint @param _token address */ function repayDebtWithReserve( uint _amount, address _token ) external { require( isDebtor[ msg.sender ], "Not approved" ); require( isReserveToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); uint value = valueOfToken( _token, _amount ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( value ); totalDebt = totalDebt.sub( value ); totalReserves = totalReserves.add( value ); emit ReservesUpdated( totalReserves ); emit RepayDebt( msg.sender, _token, _amount, value ); } /** @notice allow approved address to repay borrowed reserves with KEEPER @param _amount uint */ function repayDebtWithKEEPER( uint _amount ) external { require( isDebtor[ msg.sender ], "Not approved" ); KEEPER.burnFrom( msg.sender, _amount ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount ); totalDebt = totalDebt.sub( _amount ); emit RepayDebt( msg.sender, address(KEEPER), _amount, _amount ); } /** @notice allow approved address to withdraw assets @param _token address @param _amount uint */ function manage( address _token, uint _amount ) external { if( isLiquidityToken[ _token ] ) { require( isLiquidityManager[ msg.sender ], "Not approved" ); } else { require( isReserveManager[ msg.sender ], "Not approved" ); } uint value = valueOfToken(_token, _amount); require( value <= excessReserves(), "Insufficient reserves" ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); emit ReservesManaged( _token, _amount ); } /** @notice send epoch reward to staking contract */ function mintRewards( address _recipient, uint _amount ) external { require( isRewardManager[ msg.sender ], "Not approved" ); require( _amount <= excessReserves(), "Insufficient reserves" ); KEEPER.mint( _recipient, _amount ); emit RewardsMinted( msg.sender, _recipient, _amount ); } /** @notice returns excess reserves not backing tokens @return uint */ function excessReserves() public view returns ( uint ) { return totalReserves.sub( KEEPER.totalSupply().sub( totalDebt ) ); } /** @notice takes inventory of all tracked assets @notice always consolidate to recognized reserves before audit */ function auditReserves() external onlyOwner() { uint reserves; for( uint i = 0; i < reserveTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < liquidityTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) ) ); } totalReserves = reserves; emit ReservesUpdated( reserves ); emit ReservesAudited( reserves ); } /** @notice returns KEEPER valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) { if ( isReserveToken[ _token ] ) { // convert amount to match KEEPER decimals value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() ); } else if ( isLiquidityToken[ _token ] ) { value_ = IBondCalculator( bondCalculator[ _token ] ).valuation( _token, _amount ); } } /** @notice queue address to change boolean in mapping @param _managing MANAGING @param _address address @return bool */ function queue( MANAGING _managing, address _address ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0 reserveDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVESPENDER ) { // 1 reserveSpenderQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVETOKEN ) { // 2 reserveTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3 ReserveManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) ); } else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4 LiquidityDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5 LiquidityTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6 LiquidityManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) ); } else if ( _managing == MANAGING.DEBTOR ) { // 7 debtorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.REWARDMANAGER ) { // 8 rewardManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.SKEEPER ) { // 9 sKEEPERQueue = block.timestamp.add( secondsNeededForQueue ); } else return false; emit ChangeQueued( _managing, _address ); return true; } /** @notice verify queue then set boolean in mapping @param _managing MANAGING @param _address address @param _calculator address @return bool */ function toggle( MANAGING _managing, address _address, address _calculator ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); bool result; if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0 if ( requirements( reserveDepositorQueue, isReserveDepositor, _address ) ) { reserveDepositorQueue[ _address ] = 0; if( !listContains( reserveDepositors, _address ) ) { reserveDepositors.push( _address ); } } result = !isReserveDepositor[ _address ]; isReserveDepositor[ _address ] = result; } else if ( _managing == MANAGING.RESERVESPENDER ) { // 1 if ( requirements( reserveSpenderQueue, isReserveSpender, _address ) ) { reserveSpenderQueue[ _address ] = 0; if( !listContains( reserveSpenders, _address ) ) { reserveSpenders.push( _address ); } } result = !isReserveSpender[ _address ]; isReserveSpender[ _address ] = result; } else if ( _managing == MANAGING.RESERVETOKEN ) { // 2 if ( requirements( reserveTokenQueue, isReserveToken, _address ) ) { reserveTokenQueue[ _address ] = 0; if( !listContains( reserveTokens, _address ) ) { reserveTokens.push( _address ); } } result = !isReserveToken[ _address ]; isReserveToken[ _address ] = result; } else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3 if ( requirements( ReserveManagerQueue, isReserveManager, _address ) ) { reserveManagers.push( _address ); ReserveManagerQueue[ _address ] = 0; if( !listContains( reserveManagers, _address ) ) { reserveManagers.push( _address ); } } result = !isReserveManager[ _address ]; isReserveManager[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4 if ( requirements( LiquidityDepositorQueue, isLiquidityDepositor, _address ) ) { liquidityDepositors.push( _address ); LiquidityDepositorQueue[ _address ] = 0; if( !listContains( liquidityDepositors, _address ) ) { liquidityDepositors.push( _address ); } } result = !isLiquidityDepositor[ _address ]; isLiquidityDepositor[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5 if ( requirements( LiquidityTokenQueue, isLiquidityToken, _address ) ) { LiquidityTokenQueue[ _address ] = 0; if( !listContains( liquidityTokens, _address ) ) { liquidityTokens.push( _address ); } } result = !isLiquidityToken[ _address ]; isLiquidityToken[ _address ] = result; bondCalculator[ _address ] = _calculator; } else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6 if ( requirements( LiquidityManagerQueue, isLiquidityManager, _address ) ) { LiquidityManagerQueue[ _address ] = 0; if( !listContains( liquidityManagers, _address ) ) { liquidityManagers.push( _address ); } } result = !isLiquidityManager[ _address ]; isLiquidityManager[ _address ] = result; } else if ( _managing == MANAGING.DEBTOR ) { // 7 if ( requirements( debtorQueue, isDebtor, _address ) ) { debtorQueue[ _address ] = 0; if( !listContains( debtors, _address ) ) { debtors.push( _address ); } } result = !isDebtor[ _address ]; isDebtor[ _address ] = result; } else if ( _managing == MANAGING.REWARDMANAGER ) { // 8 if ( requirements( rewardManagerQueue, isRewardManager, _address ) ) { rewardManagerQueue[ _address ] = 0; if( !listContains( rewardManagers, _address ) ) { rewardManagers.push( _address ); } } result = !isRewardManager[ _address ]; isRewardManager[ _address ] = result; } else if ( _managing == MANAGING.SKEEPER ) { // 9 sKEEPERQueue = 0; sKEEPER = _address; result = true; } else return false; emit ChangeActivated( _managing, _address, result ); return true; } /** @notice checks requirements and returns altered structs @param queue_ mapping( address => uint ) @param status_ mapping( address => bool ) @param _address address @return bool */ function requirements( mapping( address => uint ) storage queue_, mapping( address => bool ) storage status_, address _address ) internal view returns ( bool ) { if ( !status_[ _address ] ) { require( queue_[ _address ] != 0, "Must queue" ); require( queue_[ _address ] <= block.timestamp, "Queue not expired" ); return true; } return false; } /** @notice checks array to ensure against duplicate @param _list address[] @param _token address @return bool */ function listContains( address[] storage _list, address _token ) internal view returns ( bool ) { for( uint i = 0; i < _list.length; i++ ) { if( _list[ i ] == _token ) { return true; } } return false; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IKeplerERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256 amount_) external; function mint(address account_, uint256 ammount_) external; function burnFrom(address account_, uint256 amount_) external; function vault() external returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./interfaces/IStaking.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract StakingHelper { address public immutable staking; address public immutable KEEPER; constructor ( address _staking, address _KEEPER ) { require( _staking != address(0) ); staking = _staking; require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function stake( uint _amount, bool _wrap ) external { IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount ); IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, msg.sender, _wrap ); IStaking( staking ).claim( msg.sender ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IDistributor.sol"; import "./interfaces/IiKEEPER.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./libraries/SafeMathExtended.sol"; contract oldStaking is Ownable { using SafeERC20 for IERC20; using SafeERC20 for IsKEEPER; using SafeMathExtended for uint256; using SafeMathExtended for uint32; event DistributorSet( address distributor ); event WarmupSet( uint warmup ); event IKeeperSet( address iKEEPER ); struct Epoch { uint32 length; uint32 endTime; uint32 number; uint distribute; } struct Claim { uint deposit; uint gons; uint expiry; bool lock; // prevents malicious delays } IERC20 public immutable KEEPER; IsKEEPER public immutable sKEEPER; IwTROVE public immutable wTROVE; Epoch public epoch; address public distributor; address public iKEEPER; mapping( address => Claim ) public warmupInfo; uint32 public warmupPeriod; uint gonsInWarmup; constructor (address _KEEPER, address _sKEEPER, address _wTROVE, uint32 _epochLength, uint32 _firstEpochNumber, uint32 _firstEpochTime) { require( _KEEPER != address(0) ); KEEPER = IERC20( _KEEPER ); require( _sKEEPER != address(0) ); sKEEPER = IsKEEPER( _sKEEPER ); require( _wTROVE != address(0) ); wTROVE = IwTROVE( _wTROVE ); epoch = Epoch({ length: _epochLength, number: _firstEpochNumber, endTime: _firstEpochTime, distribute: 0 }); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice stake KEEPER to enter warmup * @param _amount uint * @param _recipient address */ function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ) { rebase(); KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); if ( warmupPeriod == 0 ) { return _send( _recipient, _amount, _wrap ); } else { Claim memory info = warmupInfo[ _recipient ]; if ( !info.lock ) { require( _recipient == msg.sender, "External deposits for account are locked" ); } uint sKeeperGons = sKEEPER.gonsForBalance( _amount ); warmupInfo[ _recipient ] = Claim ({ deposit: info.deposit.add(_amount), gons: info.gons.add(sKeeperGons), expiry: epoch.number.add32(warmupPeriod), lock: info.lock }); gonsInWarmup = gonsInWarmup.add(sKeeperGons); return _amount; } } function stakeInvest( uint _stakeAmount, uint _investAmount, address _recipient, bool _wrap ) external { rebase(); uint keeperAmount = _stakeAmount.add(_investAmount.div(1e9)); KEEPER.safeTransferFrom( msg.sender, address(this), keeperAmount ); _send( _recipient, _stakeAmount, _wrap ); sKEEPER.approve(iKEEPER, _investAmount); IiKEEPER(iKEEPER).wrap(_investAmount, _recipient); } /** * @notice retrieve stake from warmup * @param _recipient address */ function claim ( address _recipient ) public returns ( uint ) { Claim memory info = warmupInfo[ _recipient ]; if ( epoch.number >= info.expiry && info.expiry != 0 ) { delete warmupInfo[ _recipient ]; gonsInWarmup = gonsInWarmup.sub(info.gons); return _send( _recipient, sKEEPER.balanceForGons( info.gons ), false); } return 0; } /** * @notice forfeit stake and retrieve KEEPER */ function forfeit() external returns ( uint ) { Claim memory info = warmupInfo[ msg.sender ]; delete warmupInfo[ msg.sender ]; gonsInWarmup = gonsInWarmup.sub(info.gons); KEEPER.safeTransfer( msg.sender, info.deposit ); return info.deposit; } /** * @notice prevent new deposits or claims from ext. address (protection from malicious activity) */ function toggleLock() external { warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock; } /** * @notice redeem sKEEPER for KEEPER * @param _amount uint * @param _trigger bool */ function unstake( uint _amount, bool _trigger ) external returns ( uint ) { if ( _trigger ) { rebase(); } uint amount = _amount; sKEEPER.safeTransferFrom( msg.sender, address(this), _amount ); KEEPER.safeTransfer( msg.sender, amount ); return amount; } /** @notice trigger rebase if epoch over */ function rebase() public { if( epoch.endTime <= uint32(block.timestamp) ) { sKEEPER.rebase( epoch.distribute, epoch.number ); epoch.endTime = epoch.endTime.add32(epoch.length); epoch.number++; if ( distributor != address(0) ) { IDistributor( distributor ).distribute(); } uint contractBalanceVal = contractBalance(); uint totalStakedVal = totalStaked(); if( contractBalanceVal <= totalStakedVal ) { epoch.distribute = 0; } else { epoch.distribute = contractBalanceVal.sub(totalStakedVal); } } } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice send staker their amount as sKEEPER or gKEEPER * @param _recipient address * @param _amount uint */ function _send( address _recipient, uint _amount, bool _wrap ) internal returns ( uint ) { if (_wrap) { sKEEPER.approve( address( wTROVE ), _amount ); uint wrapValue = wTROVE.wrap( _amount ); wTROVE.transfer( _recipient, wrapValue ); } else { sKEEPER.safeTransfer( _recipient, _amount ); // send as sKEEPER (equal unit as KEEPER) } return _amount; } /* ========== VIEW FUNCTIONS ========== */ /** @notice returns the sKEEPER index, which tracks rebase growth @return uint */ function index() public view returns ( uint ) { return sKEEPER.index(); } /** @notice returns contract KEEPER holdings, including bonuses provided @return uint */ function contractBalance() public view returns ( uint ) { return KEEPER.balanceOf( address(this) ); } function totalStaked() public view returns ( uint ) { return sKEEPER.circulatingSupply(); } function supplyInWarmup() public view returns ( uint ) { return sKEEPER.balanceForGons( gonsInWarmup ); } /* ========== MANAGERIAL FUNCTIONS ========== */ /** @notice sets the contract address for LP staking @param _address address */ function setDistributor( address _address ) external onlyOwner() { distributor = _address; emit DistributorSet( _address ); } /** * @notice set warmup period for new stakers * @param _warmupPeriod uint */ function setWarmup( uint32 _warmupPeriod ) external onlyOwner() { warmupPeriod = _warmupPeriod; emit WarmupSet( _warmupPeriod ); } function setIKeeper( address _iKEEPER ) external onlyOwner() { iKEEPER = _iKEEPER; emit IKeeperSet( _iKEEPER ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IDistributor { function distribute() external returns ( bool ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IiKEEPER is IERC20 { function wrap(uint _amount, address _recipient) external; function unwrap(uint _amount) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IWETH9.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract EthBondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint gonsPayout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ if (address(this).balance >= _amount) { // pay with WETH9 IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay IWETH9(principle).transfer(treasury, _amount); } else { IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); } ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted refundETH(); //refund user if needed return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != sKEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } function refundETH() internal { if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IsKEEPER.sol"; contract wTROVE is ERC20 { using SafeMath for uint; address public immutable TROVE; constructor(address _TROVE) ERC20("Wrapped Trove", "wTROVE") { require(_TROVE != address(0)); TROVE = _TROVE; } /** @notice wrap TROVE @param _amount uint @return uint */ function wrap( uint _amount ) external returns ( uint ) { IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount ); uint value = TROVETowTROVE( _amount ); _mint( msg.sender, value ); return value; } /** @notice unwrap TROVE @param _amount uint @return uint */ function unwrap( uint _amount ) external returns ( uint ) { _burn( msg.sender, _amount ); uint value = wTROVEToTROVE( _amount ); IsKEEPER( TROVE ).transfer( msg.sender, value ); return value; } /** @notice converts wTROVE amount to TROVE @param _amount uint @return uint */ function wTROVEToTROVE( uint _amount ) public view returns ( uint ) { return _amount.mul( IsKEEPER( TROVE ).index() ).div( 10 ** decimals() ); } /** @notice converts TROVE amount to wTROVE @param _amount uint @return uint */ function TROVETowTROVE( uint _amount ) public view returns ( uint ) { return _amount.mul( 10 ** decimals() ).div( IsKEEPER( TROVE ).index() ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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_) { _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: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract USDC is ERC20, Ownable { using SafeMath for uint256; constructor() ERC20("USDC", "USDC") { } function mint(address account_, uint256 amount_) external onlyOwner() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/IStaking.sol"; contract sKeplerERC20 is ERC20 { using SafeMath for uint256; event StakingContractUpdated(address stakingContract); event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply); event LogRebase(uint256 indexed epoch, uint256 rebase, uint256 index); address initializer; address public stakingContract; // balance used to calc rebase uint8 private constant _tokenDecimals = 9; uint INDEX; // Index Gons - tracks rebase growth uint _totalSupply; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**_tokenDecimals; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; mapping (address => mapping (address => uint256)) private _allowedValue; struct Rebase { uint epoch; uint rebase; // 18 decimals uint totalStakedBefore; uint totalStakedAfter; uint amountRebased; uint index; uint timeOccured; } Rebase[] public rebases; // past rebase data modifier onlyStakingContract() { require(msg.sender == stakingContract); _; } constructor() ERC20("Staked Keeper", "TROVE") { _setupDecimals(_tokenDecimals); initializer = msg.sender; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); } function setIndex(uint _INDEX) external { require(msg.sender == initializer); require(INDEX == 0); require(_INDEX != 0); INDEX = gonsForBalance(_INDEX); } // do this last function initialize(address _stakingContract) external { require(msg.sender == initializer); require(_stakingContract != address(0)); stakingContract = _stakingContract; _gonBalances[ stakingContract ] = TOTAL_GONS; emit Transfer(address(0x0), stakingContract, _totalSupply); emit StakingContractUpdated(_stakingContract); initializer = address(0); } /** @notice increases sKEEPER supply to increase staking balances relative to _profit @param _profit uint256 @return uint256 */ function rebase(uint256 _profit, uint _epoch) public onlyStakingContract() returns (uint256) { uint256 rebaseAmount; uint256 _circulatingSupply = circulatingSupply(); if (_profit == 0) { emit LogSupply(_epoch, block.timestamp, _totalSupply); emit LogRebase(_epoch, 0, index()); return _totalSupply; } else if (_circulatingSupply > 0) { rebaseAmount = _profit.mul(_totalSupply).div(_circulatingSupply); } else { rebaseAmount = _profit; } _totalSupply = _totalSupply.add(rebaseAmount); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); _storeRebase(_circulatingSupply, _profit, _epoch); return _totalSupply; } /** @notice emits event with data about rebase @param _previousCirculating uint @param _profit uint @param _epoch uint @return bool */ function _storeRebase(uint _previousCirculating, uint _profit, uint _epoch) internal returns (bool) { uint rebasePercent = _profit.mul(1e18).div(_previousCirculating); rebases.push(Rebase ({ epoch: _epoch, rebase: rebasePercent, // 18 decimals totalStakedBefore: _previousCirculating, totalStakedAfter: circulatingSupply(), amountRebased: _profit, index: index(), timeOccured: uint32(block.timestamp) })); emit LogSupply(_epoch, block.timestamp, _totalSupply); emit LogRebase(_epoch, rebasePercent, index()); return true; } /* =================================== VIEW FUNCTIONS ========================== */ /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[ who ].div(_gonsPerFragment); } /** * @param who The address to query. * @return The gon balance of the specified address. */ function scaledBalanceOf(address who) external view returns (uint256) { return _gonBalances[who]; } function gonsForBalance(uint amount) public view returns (uint) { return amount * _gonsPerFragment; } function balanceForGons(uint gons) public view returns (uint) { return gons / _gonsPerFragment; } // Staking contract holds excess sKEEPER function circulatingSupply() public view returns (uint) { return _totalSupply.sub(balanceOf(stakingContract)).add(IStaking(stakingContract).supplyInWarmup()); } function index() public view returns (uint) { return balanceForGons(INDEX); } function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedValue[ owner_ ][ spender ]; } /* ================================= MUTATIVE FUNCTIONS ====================== */ function transfer(address to, uint256 value) public override returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub(gonValue); _gonBalances[ to ] = _gonBalances[ to ].add(gonValue); emit Transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) public override returns (bool) { _allowedValue[ from ][ msg.sender ] = _allowedValue[ from ][ msg.sender ].sub(value); emit Approval(from, msg.sender, _allowedValue[ from ][ msg.sender ]); uint256 gonValue = gonsForBalance(value); _gonBalances[ from ] = _gonBalances[from].sub(gonValue); _gonBalances[ to ] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } function _approve(address owner, address spender, uint256 value) internal override virtual { _allowedValue[owner][spender] = value; emit Approval(owner, spender, value); } function approve(address spender, uint256 value) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = _allowedValue[ msg.sender ][ spender ].add(addedValue); emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { uint256 oldValue = _allowedValue[ msg.sender ][ spender ]; if (subtractedValue >= oldValue) { _allowedValue[ msg.sender ][ spender ] = 0; } else { _allowedValue[ msg.sender ][ spender ] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract cKEEPER is ERC20, Ownable { using SafeMath for uint; bool public requireSellerApproval; mapping( address => bool ) public isApprovedSeller; constructor() ERC20("Call Keeper", "cKEEPER") { uint initSupply = 500000000 * 1e18; _addApprovedSeller( address(this) ); _addApprovedSeller( msg.sender ); _mint( msg.sender, initSupply ); requireSellerApproval = true; } function allowOpenTrading() external onlyOwner() returns ( bool ) { requireSellerApproval = false; return requireSellerApproval; } function _addApprovedSeller( address approvedSeller_ ) internal { isApprovedSeller[approvedSeller_] = true; } function addApprovedSeller( address approvedSeller_ ) external onlyOwner() returns ( bool ) { _addApprovedSeller( approvedSeller_ ); return isApprovedSeller[approvedSeller_]; } function addApprovedSellers( address[] calldata approvedSellers_ ) external onlyOwner() returns ( bool ) { for( uint iteration_; iteration_ < approvedSellers_.length; iteration_++ ) { _addApprovedSeller( approvedSellers_[iteration_] ); } return true; } function _removeApprovedSeller( address disapprovedSeller_ ) internal { isApprovedSeller[disapprovedSeller_] = false; } function removeApprovedSeller( address disapprovedSeller_ ) external onlyOwner() returns ( bool ) { _removeApprovedSeller( disapprovedSeller_ ); return isApprovedSeller[disapprovedSeller_]; } function removeApprovedSellers( address[] calldata disapprovedSellers_ ) external onlyOwner() returns ( bool ) { for( uint iteration_; iteration_ < disapprovedSellers_.length; iteration_++ ) { _removeApprovedSeller( disapprovedSellers_[iteration_] ); } return true; } function _beforeTokenTransfer(address from_, address to_, uint256 amount_ ) internal override { require( (balanceOf(to_) > 0 || isApprovedSeller[from_] == true || !requireSellerApproval), "Account not approved to transfer cKEEPER." ); } function burn(uint256 amount_) public virtual { _burn( msg.sender, amount_ ); } function burnFrom( address account_, uint256 amount_ ) public virtual { _burnFrom( account_, amount_ ); } function _burnFrom( address account_, uint256 amount_ ) internal virtual { uint256 decreasedAllowance_ = allowance( account_, msg.sender ).sub( amount_, "ERC20: burn amount exceeds allowance"); _approve( account_, msg.sender, decreasedAllowance_ ); _burn( account_, amount_ ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; interface IBond { function redeem( address _recipient, bool _stake ) external returns ( uint ); function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ); } contract RedeemHelper is Ownable { address[] public bonds; function redeemAll( address _recipient, bool _stake ) external { for( uint i = 0; i < bonds.length; i++ ) { if ( bonds[i] != address(0) ) { if ( IBond( bonds[i] ).pendingPayoutFor( _recipient ) > 0 ) { IBond( bonds[i] ).redeem( _recipient, _stake ); } } } } function addBondContract( address _bond ) external onlyOwner() { require( _bond != address(0) ); bonds.push( _bond ); } function removeBondContract( uint _index ) external onlyOwner() { bonds[ _index ] = address(0); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract KEEPERCircSupply is Ownable { using SafeMath for uint; address public KEEPER; address[] public nonCirculatingKEEPERAddresses; constructor (address _KEEPER) { KEEPER = _KEEPER; } function KEEPERCirculatingSupply() external view returns (uint) { uint _totalSupply = IERC20( KEEPER ).totalSupply(); uint _circulatingSupply = _totalSupply.sub( getNonCirculatingKEEPER() ); return _circulatingSupply; } function getNonCirculatingKEEPER() public view returns ( uint ) { uint _nonCirculatingKEEPER; for( uint i=0; i < nonCirculatingKEEPERAddresses.length; i = i.add( 1 ) ) { _nonCirculatingKEEPER = _nonCirculatingKEEPER.add( IERC20( KEEPER ).balanceOf( nonCirculatingKEEPERAddresses[i] ) ); } return _nonCirculatingKEEPER; } function setNonCirculatingKEEPERAddresses( address[] calldata _nonCirculatingAddresses ) external onlyOwner() returns ( bool ) { nonCirculatingKEEPERAddresses = _nonCirculatingAddresses; return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/ITreasury.sol"; import "../interfaces/IStaking.sol"; interface IcKEEPER { function burnFrom( address account_, uint256 amount_ ) external; } contract cKeeperExercise is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; address public immutable cKEEPER; address public immutable KEEPER; address public immutable USDC; address public immutable treasury; address public staking; uint private constant CLIFF = 250000 * 10**9; // Minimum KEEPER supply to exercise uint private constant TOUCHDOWN = 5000000 * 10**9; // Maximum KEEPER supply for percent increase uint private constant Y_INCREASE = 35000; // Increase from CLIFF to TOUCHDOWN is 3.5%. 4 decimals used // uint private constant SLOPE = Y_INCREASE.div(TOUCHDOWN.sub(CLIFF)); // m = (y2 - y1) / (x2 - x1) struct Term { uint initPercent; // 4 decimals ( 5000 = 0.5% ) uint claimed; uint max; } mapping(address => Term) public terms; mapping(address => address) public walletChange; constructor( address _cKEEPER, address _KEEPER, address _USDC, address _treasury, address _staking ) { require( _cKEEPER != address(0) ); cKEEPER = _cKEEPER; require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _USDC != address(0) ); USDC = _USDC; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; } function setStaking( address _staking ) external onlyOwner() { require( _staking != address(0) ); staking = _staking; } // Sets terms for a new wallet function setTerms(address _vester, uint _amountCanClaim, uint _rate ) external onlyOwner() returns ( bool ) { terms[_vester].max = _amountCanClaim; terms[_vester].initPercent = _rate; return true; } // Sets terms for multiple wallets function setTermsMultiple(address[] calldata _vesters, uint[] calldata _amountCanClaims, uint[] calldata _rates ) external onlyOwner() returns ( bool ) { for (uint i=0; i < _vesters.length; i++) { terms[_vesters[i]].max = _amountCanClaims[i]; terms[_vesters[i]].initPercent = _rates[i]; } return true; } // Allows wallet to redeem cKEEPER for KEEPER function exercise( uint _amount, bool _stake, bool _wrap ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' ); uint usdcAmount = _amount.div(1e12); IERC20( USDC ).safeTransferFrom( msg.sender, address( this ), usdcAmount ); IcKEEPER( cKEEPER ).burnFrom( msg.sender, _amount ); IERC20( USDC ).approve( treasury, usdcAmount ); uint KEEPERToSend = ITreasury( treasury ).deposit( usdcAmount, USDC, 0 ); terms[ msg.sender ].claimed = info.claimed.add( _amount ); if ( _stake ) { IERC20( KEEPER ).approve( staking, KEEPERToSend ); IStaking( staking ).stake( KEEPERToSend, msg.sender, _wrap ); } else { IERC20( KEEPER ).safeTransfer( msg.sender, KEEPERToSend ); } return true; } // Allows wallet owner to transfer rights to a new address function pushWalletChange( address _newWallet ) external returns ( bool ) { require( terms[ msg.sender ].initPercent != 0 ); walletChange[ msg.sender ] = _newWallet; return true; } // Allows wallet to pull rights from an old address function pullWalletChange( address _oldWallet ) external returns ( bool ) { require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" ); walletChange[ _oldWallet ] = address(0); terms[ msg.sender ] = terms[ _oldWallet ]; delete terms[ _oldWallet ]; return true; } // Amount a wallet can redeem based on current supply function redeemableFor( address _vester ) public view returns (uint) { return redeemable( terms[ _vester ]); } function redeemable( Term memory _info ) internal view returns ( uint ) { if ( _info.initPercent == 0 ) { return 0; } uint keeperSupply = IERC20( KEEPER ).totalSupply(); if (keeperSupply < CLIFF) { return 0; } else if (keeperSupply > TOUCHDOWN) { keeperSupply = TOUCHDOWN; } uint percent = Y_INCREASE.mul(keeperSupply.sub(CLIFF)).div(TOUCHDOWN.sub(CLIFF)).add(_info.initPercent); return ( keeperSupply.mul( percent ).mul( 1000 ) ).sub( _info.claimed ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract aKeeperStake2 is Ownable { using SafeMath for uint256; IERC20 public aKEEPER; IERC20 public KEEPER; address public staking; mapping( address => uint ) public depositInfo; uint public depositDeadline; uint public withdrawStart; uint public withdrawDeadline; constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) { require( _aKEEPER != address(0) ); aKEEPER = IERC20(_aKEEPER); depositDeadline = _depositDeadline; withdrawStart = _withdrawStart; withdrawDeadline = _withdrawDeadline; } function setDepositDeadline(uint _depositDeadline) external onlyOwner() { depositDeadline = _depositDeadline; } function setWithdrawStart(uint _withdrawStart) external onlyOwner() { withdrawStart = _withdrawStart; } function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() { withdrawDeadline = _withdrawDeadline; } function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() { KEEPER = IERC20(_KEEPER); staking = _staking; } function depositaKeeper(uint amount) external { require(block.timestamp < depositDeadline, "Deadline passed."); aKEEPER.transferFrom(msg.sender, address(this), amount); depositInfo[msg.sender] = depositInfo[msg.sender].add(amount); } // function withdrawaKeeper() external { // require(block.timestamp > withdrawStart, "Not started."); // uint amount = depositInfo[msg.sender].mul(110).div(100); // require(amount > 0, "No deposit present."); // delete depositInfo[msg.sender]; // aKEEPER.transfer(msg.sender, amount); // } function migrate() external { require(block.timestamp > withdrawStart, "Not started."); require( address(KEEPER) != address(0) ); uint amount = depositInfo[msg.sender].mul(110).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.transfer(msg.sender, amount); } function migrateTrove(bool _wrap) external { require(block.timestamp > withdrawStart, "Not started."); require( staking != address(0) ); uint amount = depositInfo[msg.sender].mul(110).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); } function withdrawAll() external onlyOwner() { require(block.timestamp > withdrawDeadline, "Deadline not yet passed."); uint256 Keeperamount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, Keeperamount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract aKeeperStake is Ownable { using SafeMath for uint256; IERC20 public aKEEPER; IERC20 public KEEPER; address public staking; mapping( address => uint ) public depositInfo; uint public depositDeadline; uint public withdrawStart; uint public withdrawDeadline; constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) { require( _aKEEPER != address(0) ); aKEEPER = IERC20(_aKEEPER); depositDeadline = _depositDeadline; withdrawStart = _withdrawStart; withdrawDeadline = _withdrawDeadline; } function setDepositDeadline(uint _depositDeadline) external onlyOwner() { depositDeadline = _depositDeadline; } function setWithdrawStart(uint _withdrawStart) external onlyOwner() { withdrawStart = _withdrawStart; } function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() { withdrawDeadline = _withdrawDeadline; } function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() { KEEPER = IERC20(_KEEPER); staking = _staking; } function depositaKeeper(uint amount) external { require(block.timestamp < depositDeadline, "Deadline passed."); aKEEPER.transferFrom(msg.sender, address(this), amount); depositInfo[msg.sender] = depositInfo[msg.sender].add(amount); } function withdrawaKeeper() external { require(block.timestamp > withdrawStart, "Not started."); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; aKEEPER.transfer(msg.sender, amount); } function migrate() external { require( address(KEEPER) != address(0) ); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.transfer(msg.sender, amount); } function migrateTrove(bool _wrap) external { require( staking != address(0) ); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); } function withdrawAll() external onlyOwner() { require(block.timestamp > withdrawDeadline, "Deadline not yet passed."); uint256 Keeperamount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, Keeperamount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract oldaKeeperRedeem is Ownable { using SafeMath for uint256; IERC20 public KEEPER; IERC20 public aKEEPER; address public staking; event KeeperRedeemed(address tokenOwner, uint256 amount); event TroveRedeemed(address tokenOwner, uint256 amount); constructor(address _KEEPER, address _aKEEPER, address _staking) { require( _KEEPER != address(0) ); require( _aKEEPER != address(0) ); require( _staking != address(0) ); KEEPER = IERC20(_KEEPER); aKEEPER = IERC20(_aKEEPER); staking = _staking; } function setStaking(address _staking) external onlyOwner() { require( _staking != address(0) ); staking = _staking; } function migrate(uint256 amount) public { require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance"); aKEEPER.transferFrom(msg.sender, address(this), amount); KEEPER.transfer(msg.sender, amount); emit KeeperRedeemed(msg.sender, amount); } function migrateTrove(uint256 amount, bool _wrap) public { require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance"); aKEEPER.transferFrom(msg.sender, address(this), amount); IERC20( KEEPER ).approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); emit TroveRedeemed(msg.sender, amount); } function withdraw() external onlyOwner() { uint256 amount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/AggregateV3Interface.sol"; contract aKeeperPresale is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; IERC20 public aKEEPER; address public USDC; address public USDT; address public DAI; address public wBTC; address public gnosisSafe; mapping( address => uint ) public amountInfo; uint deadline; AggregatorV3Interface internal ethPriceFeed; AggregatorV3Interface internal btcPriceFeed; event aKeeperRedeemed(address tokenOwner, uint amount); constructor(address _aKEEPER, address _USDC, address _USDT, address _DAI, address _wBTC, address _ethFeed, address _btcFeed, address _gnosisSafe, uint _deadline) { require( _aKEEPER != address(0) ); require( _USDC != address(0) ); require( _USDT != address(0) ); require( _DAI != address(0) ); require( _wBTC != address(0) ); require( _ethFeed != address(0) ); require( _btcFeed != address(0) ); aKEEPER = IERC20(_aKEEPER); USDC = _USDC; USDT = _USDT; DAI = _DAI; wBTC = _wBTC; gnosisSafe = _gnosisSafe; deadline = _deadline; ethPriceFeed = AggregatorV3Interface( _ethFeed ); btcPriceFeed = AggregatorV3Interface( _btcFeed ); } function setDeadline(uint _deadline) external onlyOwner() { deadline = _deadline; } function ethAssetPrice() public view returns (int) { ( , int price, , , ) = ethPriceFeed.latestRoundData(); return price; } function btcAssetPrice() public view returns (int) { ( , int price, , , ) = btcPriceFeed.latestRoundData(); return price; } function maxAmount() internal pure returns (uint) { return 100000000000; } function getTokens(address principle, uint amount) external { require(block.timestamp < deadline, "Deadline has passed."); require(principle == USDC || principle == USDT || principle == DAI || principle == wBTC, "Token is not acceptable."); require(IERC20(principle).balanceOf(msg.sender) >= amount, "Not enough token amount."); // Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100 uint aKeeperAmount; if (principle == DAI) { aKeeperAmount = amount.div(1e11); } else if (principle == wBTC) { aKeeperAmount = amount.mul(uint(btcAssetPrice())).div(1e9); } else { aKeeperAmount = amount.mul(1e1); } require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens."); IERC20(principle).safeTransferFrom(msg.sender, gnosisSafe, amount); aKEEPER.transfer(msg.sender, aKeeperAmount); amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount); emit aKeeperRedeemed(msg.sender, aKeeperAmount); } function getTokensEth() external payable { require(block.timestamp < deadline, "Deadline has passed."); uint amount = msg.value; // Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100 uint aKeeperAmount = amount.mul(uint(ethAssetPrice())).div(1e19); require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens."); safeTransferETH(gnosisSafe, amount); aKEEPER.transfer(msg.sender, aKeeperAmount); amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount); emit aKeeperRedeemed(msg.sender, aKeeperAmount); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } function withdraw() external onlyOwner() { uint256 amount = aKEEPER.balanceOf(address(this)); aKEEPER.transfer(msg.sender, amount); } function withdrawEth() external onlyOwner() { safeTransferETH(gnosisSafe, address(this).balance); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IWETH9.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract EthBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) { require( _depositor != address(0), "Invalid address" ); require( msg.value == 0 || _amount == msg.value, "Amount should be equal to ETH transferred"); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ if (address(this).balance >= _amount) { // pay with WETH9 IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay IWETH9(principle).transfer(treasury, _amount); } else { IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); } ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted refundETH(); //refund user if needed return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } function refundETH() internal { if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract aKeeperAirdrop is Ownable { using SafeMath for uint; IERC20 public aKEEPER; IERC20 public USDC; address public gnosisSafe; constructor(address _aKEEPER, address _USDC, address _gnosisSafe) { require( _aKEEPER != address(0) ); require( _USDC != address(0) ); aKEEPER = IERC20(_aKEEPER); USDC = IERC20(_USDC); gnosisSafe = _gnosisSafe; } receive() external payable { } function airdropTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { aKEEPER.transfer(_recipients[i], _amounts[i]); } } function refundUsdcTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { USDC.transfer(_recipients[i], _amounts[i]); } } function refundEth(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { safeTransferETH(_recipients[i], _amounts[i]); } } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } function withdraw() external onlyOwner() { uint256 amount = aKEEPER.balanceOf(address(this)); aKEEPER.transfer(msg.sender, amount); } function withdrawUsdc() external onlyOwner() { uint256 amount = USDC.balanceOf(address(this)); USDC.transfer(gnosisSafe, amount); } function withdrawEth() external onlyOwner() { safeTransferETH(gnosisSafe, address(this).balance); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ILPCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; import "./interfaces/ISPV.sol"; import "./interfaces/IStaking.sol"; contract Treasury is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event Deposit( address indexed token, uint amount, uint value ); event DepositEth( uint amount, uint value ); event Sell( address indexed token, uint indexed amount, uint indexed price ); event SellEth( uint indexed amount, uint indexed price ); event ReservesWithdrawn( address indexed caller, address indexed token, uint amount ); event ReservesUpdated( uint indexed totalReserves ); event ReservesAudited( uint indexed totalReserves ); event ChangeActivated( MANAGING indexed managing, address activated, bool result ); event SPVUpdated( address indexed spv ); enum MANAGING { RESERVETOKEN, LIQUIDITYTOKEN, VARIABLETOKEN } struct PriceFeed { address feed; uint decimals; } IKeplerERC20 immutable KEEPER; uint public constant keeperDecimals = 9; uint public immutable priceAdjust; // 4 decimals. 1000 = 0.1 address[] public reserveTokens; mapping( address => bool ) public isReserveToken; address[] public variableTokens; mapping( address => bool ) public isVariableToken; address[] public liquidityTokens; mapping( address => bool ) public isLiquidityToken; mapping( address => address ) public lpCalculator; // bond calculator for liquidity token mapping( address => PriceFeed ) public priceFeeds; // price feeds for variable token uint public totalReserves; uint public spvDebt; uint public daoDebt; uint public ownerDebt; uint public reserveLastAudited; AggregatorV3Interface internal ethPriceFeed; address public staking; address public vesting; address public SPV; address public immutable DAO; uint public daoRatio; // 4 decimals. 1000 = 0.1 uint public spvRatio; // 4 decimals. 7000 = 0.7 uint public vestingRatio; // 4 decimals. 1000 = 0.1 uint public stakeRatio; // 4 decimals. 9000 = 0.9 uint public lcv; // 4 decimals. 1000 = 0.1 uint public keeperSold; uint public initPrice; // To deposit initial reserves when price is undefined (Keeper supply = 0) constructor (address _KEEPER, address _USDC, address _USDT, address _DAI, address _DAO, address _vesting, address _ethPriceFeed, uint _priceAdjust, uint _initPrice) { require( _KEEPER != address(0) ); KEEPER = IKeplerERC20(_KEEPER); require( _DAO != address(0) ); DAO = _DAO; require( _vesting != address(0) ); vesting = _vesting; isReserveToken[ _USDC] = true; reserveTokens.push( _USDC ); isReserveToken[ _USDT] = true; reserveTokens.push( _USDT ); isReserveToken[ _DAI ] = true; reserveTokens.push( _DAI ); ethPriceFeed = AggregatorV3Interface( _ethPriceFeed ); priceAdjust = _priceAdjust; initPrice = _initPrice; } function treasuryInitialized() external onlyOwner() { initPrice = 0; } function setSPV(address _SPV) external onlyOwner() { require( _SPV != address(0), "Cannot be 0"); SPV = _SPV; emit SPVUpdated( SPV ); } function setVesting(address _vesting) external onlyOwner() { require( _vesting != address(0), "Cannot be 0"); vesting = _vesting; } function setStaking(address _staking) external onlyOwner() { require( _staking != address(0), "Cannot be 0"); staking = _staking; } function setLcv(uint _lcv) external onlyOwner() { require( lcv == 0 || _lcv <= lcv.mul(3).div(2), "LCV cannot change sharp" ); lcv = _lcv; } function setTreasuryRatio(uint _daoRatio, uint _spvRatio, uint _vestingRatio, uint _stakeRatio) external onlyOwner() { require( _daoRatio <= 1000, "DAO more than 10%" ); require( _spvRatio <= 7000, "SPV more than 70%" ); require( _vestingRatio <= 2000, "Vesting more than 20%" ); require( _stakeRatio >= 1000 && _stakeRatio <= 10000, "Stake ratio error" ); daoRatio = _daoRatio; spvRatio = _spvRatio; vestingRatio = _vestingRatio; stakeRatio = _stakeRatio; } function getPremium(uint _price) public view returns (uint) { return _price.mul( lcv ).mul( keeperSold ).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) ).div( 1e4 ); } function getPrice() public view returns ( uint ) { if (initPrice != 0) { return initPrice; } else { return totalReserves.add(ownerDebt).add( ISPV(SPV).totalValue() ).add( priceAdjust ).mul(10 ** keeperDecimals).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) ); } } function ethAssetPrice() public view returns (uint) { ( , int price, , , ) = ethPriceFeed.latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 1e8 ); } function variableAssetPrice(address _address, uint _decimals) public view returns (uint) { ( , int price, , , ) = AggregatorV3Interface(_address).latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** _decimals ); } function EthToUSD( uint _amount ) internal view returns ( uint ) { return _amount.mul( ethAssetPrice() ).div( 1e18 ); } function auditTotalReserves() public { uint reserves; for( uint i = 0; i < reserveTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < liquidityTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < variableTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( variableTokens[ i ], IERC20Extended( variableTokens[ i ] ).balanceOf( address(this) ) ) ); } reserves = reserves.add( EthToUSD(address(this).balance) ); totalReserves = reserves; reserveLastAudited = block.timestamp; emit ReservesUpdated( reserves ); emit ReservesAudited( reserves ); } /** @notice allow depositing an asset for KEEPER @param _amount uint @param _token address @return send_ uint */ function deposit( uint _amount, address _token, bool _stake ) external returns ( uint send_ ) { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); // uint daoAmount = _amount.mul(daoRatio).div(1e4); // IERC20Extended( _token ).safeTransfer( DAO, daoAmount ); uint value = valueOfToken(_token, _amount); // uint daoValue = value.mul(daoRatio).div(1e4); // mint KEEPER needed and store amount of rewards for distribution totalReserves = totalReserves.add( value ); send_ = sendOrStake(msg.sender, value, _stake); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value ); } function depositEth( uint _amount, bool _stake ) external payable returns ( uint send_ ) { require( _amount == msg.value, "Amount should be equal to ETH transferred"); // uint daoAmount = _amount.mul(daoRatio).div(1e4); // safeTransferETH(DAO, daoAmount); uint value = EthToUSD( _amount ); // uint daoValue = value.mul(daoRatio).div(1e4); // mint KEEPER needed and store amount of rewards for distribution totalReserves = totalReserves.add( value ); send_ = sendOrStake(msg.sender, value, _stake); emit ReservesUpdated( totalReserves ); emit DepositEth( _amount, value ); } function sendOrStake(address _recipient, uint _value, bool _stake) internal returns (uint send_) { send_ = _value.mul( 10 ** keeperDecimals ).div( getPrice() ); if ( _stake ) { KEEPER.mint( address(this), send_ ); KEEPER.approve( staking, send_ ); IStaking( staking ).stake( send_, _recipient, false ); } else { KEEPER.mint( _recipient, send_ ); } uint vestingAmount = send_.mul(vestingRatio).div(1e4); KEEPER.mint( vesting, vestingAmount ); } /** @notice allow to burn KEEPER for reserves @param _amount uint of keeper @param _token address */ function sell( uint _amount, address _token ) external { require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions (uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount); uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) ); uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals ); uint tokenAmount = reserveLoss.mul( 10 ** IERC20Extended( _token ).decimals() ).div( 10 ** keeperDecimals ); totalReserves = totalReserves.sub( reserveLoss ); emit ReservesUpdated( totalReserves ); uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice); uint daoAmount = tokenAmount.sub(sellAmount); IERC20Extended(_token).safeTransfer(msg.sender, sellAmount); IERC20Extended(_token).safeTransfer(DAO, daoAmount); emit Sell( _token, _amount, sellPrice ); } function sellEth( uint _amount ) external { (uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount); uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) ); uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals ); uint tokenAmount = reserveLoss.mul(10 ** 18).div( ethAssetPrice() ); totalReserves = totalReserves.sub( reserveLoss ); emit ReservesUpdated( totalReserves ); uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice); uint daoAmount = tokenAmount.sub(sellAmount); safeTransferETH(msg.sender, sellAmount); safeTransferETH(DAO, daoAmount); emit SellEth( _amount, sellPrice ); } function sellKeeperBurn(address _sender, uint _amount) internal returns (uint price, uint premium, uint sellPrice) { price = getPrice(); premium = getPremium(price); sellPrice = price.sub(premium); KEEPER.burnFrom( _sender, _amount ); keeperSold = keeperSold.add( _amount ); uint stakeRewards = _amount.mul(stakeRatio).mul(premium).div(price).div(1e4); KEEPER.mint( address(this), stakeRewards ); KEEPER.approve( staking, stakeRewards ); IStaking( staking ).addRebaseReward( stakeRewards ); } function unstakeMint(uint _amount) external { require( msg.sender == staking, "Not allowed." ); KEEPER.mint(msg.sender, _amount); } function initDeposit( address _token, uint _amount ) external payable onlyOwner() { require( initPrice != 0, "Already initialized" ); uint value; if ( _token == address(0) && msg.value != 0 ) { require( _amount == msg.value, "Amount mismatch" ); value = EthToUSD( _amount ); } else { IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.add( value ); uint send_ = value.mul( 10 ** keeperDecimals ).div( getPrice() ); KEEPER.mint( msg.sender, send_ ); } /** @notice allow owner multisig to withdraw assets on debt (for safe investments) @param _token address @param _amount uint */ function incurDebt( address _token, uint _amount, bool isEth ) external onlyOwner() { uint value; if ( _token == address(0) && isEth ) { safeTransferETH(msg.sender, _amount); value = EthToUSD( _amount ); } else { IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.sub( value ); ownerDebt = ownerDebt.add(value); emit ReservesUpdated( totalReserves ); emit ReservesWithdrawn( msg.sender, _token, _amount ); } function repayDebt( address _token, uint _amount, bool isEth ) external payable onlyOwner() { uint value; if ( isEth ) { require( msg.value == _amount, "Amount mismatch" ); value = EthToUSD( _amount ); } else { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.add( value ); if ( value > ownerDebt ) { uint daoProfit = _amount.mul( daoRatio ).mul( value.sub(ownerDebt) ).div( value ).div(1e4); if ( isEth ) { safeTransferETH( DAO, daoProfit ); } else { IERC20Extended( _token ).safeTransfer( DAO, daoProfit ); } value = ownerDebt; } ownerDebt = ownerDebt.sub(value); emit ReservesUpdated( totalReserves ); } function SPVDeposit( address _token, uint _amount ) external { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); uint value = valueOfToken(_token, _amount); totalReserves = totalReserves.add( value ); if ( value > spvDebt ) { value = spvDebt; } spvDebt = spvDebt.sub(value); emit ReservesUpdated( totalReserves ); } function SPVWithdraw( address _token, uint _amount ) external { require( msg.sender == SPV, "Only SPV" ); address SPVWallet = ISPV( SPV ).SPVWallet(); uint value = valueOfToken(_token, _amount); uint totalValue = totalReserves.add( ISPV(SPV).totalValue() ).add( ownerDebt ); require( spvDebt.add(value) < totalValue.mul(spvRatio).div(1e4), "Debt exceeded" ); spvDebt = spvDebt.add(value); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( SPVWallet, _amount ); } function DAOWithdraw( address _token, uint _amount, bool isEth ) external { require( msg.sender == DAO, "Only DAO Allowed" ); uint value; if ( _token == address(0) && isEth ) { value = EthToUSD( _amount ); } else { value = valueOfToken(_token, _amount); } uint daoProfit = ISPV( SPV ).totalProfit().mul( daoRatio ).div(1e4); require( daoDebt.add(value) <= daoProfit, "Too much" ); if ( _token == address(0) && isEth ) { safeTransferETH(DAO, _amount); } else { IERC20Extended( _token ).safeTransfer( DAO, _amount ); } totalReserves = totalReserves.sub( value ); daoDebt = daoDebt.add(value); emit ReservesUpdated( totalReserves ); emit ReservesWithdrawn( DAO, _token, _amount ); } /** @notice returns KEEPER valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) { if ( isReserveToken[ _token ] ) { // convert amount to match KEEPER decimals value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() ); } else if ( isLiquidityToken[ _token ] ) { value_ = ILPCalculator( lpCalculator[ _token ] ).valuationUSD( _token, _amount ); } else if ( isVariableToken[ _token ] ) { value_ = _amount.mul(variableAssetPrice( priceFeeds[_token].feed, priceFeeds[_token].decimals )).div( 10 ** IERC20Extended( _token ).decimals() ); } } /** @notice verify queue then set boolean in mapping @param _managing MANAGING @param _address address @param _calculatorFeed address @return bool */ function toggle( MANAGING _managing, address _address, address _calculatorFeed, uint decimals ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); bool result; if ( _managing == MANAGING.RESERVETOKEN ) { // 0 if( !listContains( reserveTokens, _address ) ) { reserveTokens.push( _address ); } result = !isReserveToken[ _address ]; isReserveToken[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 1 if( !listContains( liquidityTokens, _address ) ) { liquidityTokens.push( _address ); } result = !isLiquidityToken[ _address ]; isLiquidityToken[ _address ] = result; lpCalculator[ _address ] = _calculatorFeed; } else if ( _managing == MANAGING.VARIABLETOKEN ) { // 2 if( !listContains( variableTokens, _address ) ) { variableTokens.push( _address ); } result = !isVariableToken[ _address ]; isVariableToken[ _address ] = result; priceFeeds[ _address ] = PriceFeed({ feed: _calculatorFeed, decimals: decimals }); } else return false; emit ChangeActivated( _managing, _address, result ); return true; } /** @notice checks array to ensure against duplicate @param _list address[] @param _token address @return bool */ function listContains( address[] storage _list, address _token ) internal view returns ( bool ) { for( uint i = 0; i < _list.length; i++ ) { if( _list[ i ] == _token ) { return true; } } return false; } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; 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: AGPL-3.0-or-later pragma solidity 0.7.5; interface ILPCalculator { function valuationUSD( address _token, uint _amount ) external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IKeplerERC20 is IERC20 { function decimals() external view returns (uint8); function mint(address account_, uint256 ammount_) external; function burn(uint256 amount_) external; function burnFrom(address account_, uint256 amount_) external; function vault() external returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ISPV { function SPVWallet() external view returns ( address ); function totalValue() external view returns ( uint ); function totalProfit() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IStaking { function stake(uint _amount, address _recipient, bool _wrap) external; function addRebaseReward( uint _amount ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract aKeeperRedeem is Ownable { using SafeMath for uint256; IERC20 public KEEPER; IERC20 public aKEEPER; address public staking; uint public multiplier; // multiplier is 4 decimals i.e. 1000 = 0.1 event KeeperRedeemed(address tokenOwner, uint256 amount); constructor(address _aKEEPER, address _KEEPER, address _staking, uint _multiplier) { require( _aKEEPER != address(0) ); require( _KEEPER != address(0) ); require( _multiplier != 0 ); aKEEPER = IERC20(_aKEEPER); KEEPER = IERC20(_KEEPER); staking = _staking; multiplier = _multiplier; // reduce gas fees of migrate-stake by pre-approving large amount KEEPER.approve( staking, 1e25); } function migrate(uint256 amount, bool _stake, bool _wrap) public { aKEEPER.transferFrom(msg.sender, address(this), amount); uint keeperAmount = amount.mul(multiplier).div(1e4); if ( _stake && staking != address( 0 ) ) { IStaking( staking ).stake( keeperAmount, msg.sender, _wrap ); } else { KEEPER.transfer(msg.sender, keeperAmount); } emit KeeperRedeemed(msg.sender, keeperAmount); } function withdraw() external onlyOwner() { uint256 amount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IUniswapV2Pair.sol"; contract SPV is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event TokenAdded( address indexed token, PRICETYPE indexed priceType, uint indexed price ); event TokenPriceUpdate( address indexed token, uint indexed price ); event TokenPriceTypeUpdate( address indexed token, PRICETYPE indexed priceType ); event TokenRemoved( address indexed token ); event ValueAudited( uint indexed total ); event TreasuryWithdrawn( address indexed token, uint indexed amount ); event TreasuryReturned( address indexed token, uint indexed amount ); uint public constant keeperDecimals = 9; enum PRICETYPE { STABLE, CHAINLINK, UNISWAP, MANUAL } struct TokenPrice { address token; PRICETYPE priceType; uint price; // At keeper decimals } TokenPrice[] public tokens; struct ChainlinkPriceFeed { address feed; uint decimals; } mapping( address => ChainlinkPriceFeed ) public chainlinkPriceFeeds; mapping( address => address ) public uniswapPools; // The other token must be a stablecoin address public immutable treasury; address public SPVWallet; uint public totalValue; uint public totalProfit; uint public spvRecordedValue; uint public recordTime; uint public profitInterval; bool public allowUpdate; // False when SPV is transferring funds constructor (address _treasury, address _USDC, address _USDT, address _DAI, address _SPVWallet, uint _profitInterval) { require( _treasury != address(0) ); treasury = _treasury; require( _SPVWallet != address(0) ); SPVWallet = _SPVWallet; tokens.push(TokenPrice({ token: _USDC, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); tokens.push(TokenPrice({ token: _USDT, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); tokens.push(TokenPrice({ token: _DAI, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); recordTime = block.timestamp; require( _profitInterval > 0, "Interval cannot be 0" ); profitInterval = _profitInterval; spvRecordedValue = 0; allowUpdate = true; updateTotalValue(); } function enableUpdates() external onlyOwner() { allowUpdate = true; } function disableUpdates() external onlyOwner() { allowUpdate = false; } function setInterval( uint _profitInterval ) external onlyOwner() { require( _profitInterval > 0, "Interval cannot be 0" ); profitInterval = _profitInterval; } function chainlinkTokenPrice(address _token) public view returns (uint) { ( , int price, , , ) = AggregatorV3Interface( chainlinkPriceFeeds[_token].feed ).latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** chainlinkPriceFeeds[_token].decimals ); } function uniswapTokenPrice(address _token) public view returns (uint) { address _pair = uniswapPools[_token]; ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint reserve; address reserveToken; uint tokenAmount; if ( IUniswapV2Pair( _pair ).token0() == _token ) { reserveToken = IUniswapV2Pair( _pair ).token1(); reserve = reserve1; tokenAmount = reserve0; } else { reserveToken = IUniswapV2Pair( _pair ).token0(); reserve = reserve0; tokenAmount = reserve1; } return reserve.mul(10 ** keeperDecimals).mul( 10 ** IERC20Extended(_token).decimals() ).div( tokenAmount ).div( 10 ** IERC20Extended(reserveToken).decimals() ); } function setNewTokenPrice(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) internal returns (uint tokenPrice) { if (_priceType == PRICETYPE.STABLE) { tokenPrice = 10 ** keeperDecimals; } else if (_priceType == PRICETYPE.CHAINLINK) { chainlinkPriceFeeds[_token] = ChainlinkPriceFeed({ feed: _feedOrPool, decimals: _decimals }); tokenPrice = chainlinkTokenPrice(_token); } else if (_priceType == PRICETYPE.UNISWAP) { uniswapPools[_token] = _feedOrPool; tokenPrice = uniswapTokenPrice(_token); } else if (_priceType == PRICETYPE.MANUAL) { tokenPrice = _price; } else { tokenPrice = 0; } } function addToken(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) external onlyOwner() { uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price); require(tokenPrice > 0, "Token price cannot be 0"); tokens.push(TokenPrice({ token: _token, priceType: _priceType, price: tokenPrice })); updateTotalValue(); emit TokenAdded(_token, _priceType, tokenPrice); } function updateTokenPrice( uint _index, address _token, uint _price ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); require( tokens[ _index ].priceType == PRICETYPE.MANUAL, "Only manual tokens can be updated" ); tokens[ _index ].price = _price; updateTotalValue(); emit TokenPriceUpdate(_token, _price); } function updateTokenPriceType( uint _index, address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); tokens[ _index ].priceType = _priceType; uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price); require(tokenPrice > 0, "Token price cannot be 0"); tokens[ _index ].price = tokenPrice; updateTotalValue(); emit TokenPriceTypeUpdate(_token, _priceType); emit TokenPriceUpdate(_token, tokenPrice); } function removeToken( uint _index, address _token ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); tokens[ _index ] = tokens[tokens.length-1]; tokens.pop(); updateTotalValue(); emit TokenRemoved(_token); } function getTokenBalance( uint _index ) internal view returns (uint) { address _token = tokens[ _index ].token; return IERC20Extended(_token).balanceOf( SPVWallet ).mul(tokens[ _index ].price).div( 10 ** IERC20Extended( _token ).decimals() ); } function auditTotalValue() external { if ( allowUpdate ) { uint newValue; for ( uint i = 0; i < tokens.length; i++ ) { PRICETYPE priceType = tokens[i].priceType; if (priceType == PRICETYPE.CHAINLINK) { tokens[i].price = chainlinkTokenPrice(tokens[i].token); } else if (priceType == PRICETYPE.UNISWAP) { tokens[i].price = uniswapTokenPrice(tokens[i].token); } newValue = newValue.add( getTokenBalance(i) ); } totalValue = newValue; emit ValueAudited(totalValue); } } function calculateProfits() external { require( recordTime.add( profitInterval ) <= block.timestamp, "Not yet" ); require( msg.sender == SPVWallet || msg.sender == ITreasury( treasury ).DAO(), "Not allowed" ); recordTime = block.timestamp; updateTotalValue(); uint currentValue; uint treasuryDebt = ITreasury( treasury ).spvDebt(); if ( treasuryDebt > totalValue ) { currentValue = 0; } else { currentValue = totalValue.sub(treasuryDebt); } if ( currentValue > spvRecordedValue ) { uint profit = currentValue.sub( spvRecordedValue ); spvRecordedValue = currentValue; totalProfit = totalProfit.add(profit); } } function treasuryWithdraw( uint _index, address _token, uint _amount ) external { require( msg.sender == SPVWallet, "Only SPV Wallet allowed" ); require( _token == tokens[ _index ].token, "Wrong token" ); ITreasury( treasury ).SPVWithdraw( _token, _amount ); updateTotalValue(); emit TreasuryWithdrawn( _token, _amount ); } function returnToTreasury( uint _index, address _token, uint _amount ) external { require( _token == tokens[ _index ].token, "Wrong token" ); require( msg.sender == SPVWallet, "Only SPV Wallet can return." ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20Extended( _token ).approve( treasury, _amount ); ITreasury( treasury ).SPVDeposit( _token, _amount ); updateTotalValue(); emit TreasuryReturned( _token, _amount ); } function migrateTokens( address newSPV ) external onlyOwner() { for ( uint i = 0; i < tokens.length; i++ ) { address _token = tokens[ i ].token; IERC20Extended(_token).transfer(newSPV, IERC20Extended(_token).balanceOf( address(this) ) ); } safeTransferETH(newSPV, address(this).balance ); } function updateTotalValue() internal { if ( allowUpdate ) { uint newValue; for ( uint i = 0; i < tokens.length; i++ ) { newValue = newValue.add( getTokenBalance(i) ); } totalValue = newValue; } } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ITreasury { function unstakeMint( uint _amount ) external; function SPVDeposit( address _token, uint _amount ) external; function SPVWithdraw( address _token, uint _amount ) external; function DAO() external view returns ( address ); function spvDebt() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./IUniswapV2ERC20.sol"; interface IUniswapV2Pair is IUniswapV2ERC20 { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external view returns ( address ); function token1() external view returns ( address ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IUniswapV2ERC20 { function totalSupply() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IUniswapV2ERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; contract LPCalculator { using SafeMath for uint; address public immutable KEEPER; uint public constant keeperDecimals = 9; constructor ( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function getReserve( address _pair ) public view returns ( address reserveToken, uint reserve ) { ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) { reserve = reserve1; reserveToken = IUniswapV2Pair( _pair ).token1(); } else { reserve = reserve0; reserveToken = IUniswapV2Pair( _pair ).token0(); } } function valuationUSD( address _pair, uint _amount ) external view returns ( uint ) { uint totalSupply = IUniswapV2Pair( _pair ).totalSupply(); ( address reserveToken, uint reserve ) = getReserve( _pair ); return _amount.mul( reserve ).mul(2).mul( 10 ** keeperDecimals ).div( totalSupply ).div( 10 ** IERC20Extended( reserveToken ).decimals() ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/ITreasury.sol"; contract Staking is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; event Stake( address indexed recipient, uint indexed amount, uint indexed timestamp ); event Unstake( address indexed recipient, uint indexed amount, uint indexed timestamp ); uint public constant keeperDecimals = 9; IERC20 public immutable KEEPER; address public immutable treasury; uint public rate; // 6 decimals. 10000 = 0.01 = 1% uint public INDEX; // keeperDecimals decimals uint public keeperRewards; struct Rebase { uint rebaseRate; // 6 decimals uint totalStaked; uint index; uint timeOccured; } struct Epoch { uint number; uint rebaseInterval; uint nextRebase; } Epoch public epoch; Rebase[] public rebases; // past rebase data mapping(address => uint) public stakers; constructor( address _KEEPER, address _treasury, uint _rate, uint _INDEX, uint _rebaseInterval ) { require( _KEEPER != address(0) ); KEEPER = IERC20(_KEEPER); require( _treasury != address(0) ); treasury = _treasury; require( _rate != 0 ); rate = _rate; require( _INDEX != 0 ); INDEX = _INDEX; require( _rebaseInterval != 0 ); epoch = Epoch({ number: 1, rebaseInterval: _rebaseInterval, nextRebase: block.timestamp.add(_rebaseInterval) }); } function setRate( uint _rate ) external onlyOwner() { require( _rate >= rate.div(2) && _rate <= rate.mul(3).div(2), "Rate change cannot be too sharp." ); rate = _rate; } function stake( uint _amount, address _recipient, bool _wrap ) external { KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); uint _gonsAmount = getGonsAmount( _amount ); stakers[ _recipient ] = stakers[ _recipient ].add( _gonsAmount ); emit Stake( _recipient, _amount, block.timestamp ); rebase(); } function unstake( uint _amount ) external { rebase(); require( _amount <= stakerAmount(msg.sender), "Cannot unstake more than possible." ); if ( _amount > KEEPER.balanceOf( address(this) ) ) { ITreasury(treasury).unstakeMint( _amount.sub(KEEPER.balanceOf( address(this) ) ) ); } uint gonsAmount = getGonsAmount( _amount ); // Handle math precision error if ( gonsAmount > stakers[msg.sender] ) { gonsAmount = stakers[msg.sender]; } stakers[msg.sender] = stakers[ msg.sender ].sub(gonsAmount); KEEPER.safeTransfer( msg.sender, _amount ); emit Unstake( msg.sender, _amount, block.timestamp ); } function rebase() public { if (epoch.nextRebase <= block.timestamp) { uint rebasingRate = rebaseRate(); INDEX = INDEX.add( INDEX.mul( rebasingRate ).div(1e6) ); epoch.nextRebase = epoch.nextRebase.add(epoch.rebaseInterval); epoch.number++; keeperRewards = 0; rebases.push( Rebase({ rebaseRate: rebasingRate, totalStaked: KEEPER.balanceOf( address(this) ), index: INDEX, timeOccured: block.timestamp }) ); } } function stakerAmount( address _recipient ) public view returns (uint) { return getKeeperAmount(stakers[ _recipient ]); } function rebaseRate() public view returns (uint) { uint keeperBalance = KEEPER.balanceOf( address(this) ); if (keeperBalance == 0) { return rate; } else { return rate.add( keeperRewards.mul(1e6).div( KEEPER.balanceOf( address(this) ) ) ); } } function addRebaseReward( uint _amount ) external { KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); keeperRewards = keeperRewards.add( _amount ); } function getGonsAmount( uint _amount ) internal view returns (uint) { return _amount.mul(10 ** keeperDecimals).div(INDEX); } function getKeeperAmount( uint _gons ) internal view returns (uint) { return _gons.mul(INDEX).div(10 ** keeperDecimals); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; contract VaultOwned is Ownable { address internal _vault; function setVault(address vault_) external onlyOwner() returns (bool) { _vault = vault_; return true; } function vault() public view returns (address) { return _vault; } modifier onlyVault() { require(_vault == msg.sender, "VaultOwned: caller is not the Vault"); _; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract MockKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract KeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external onlyVault() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract KeeperVesting is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; IERC20 public immutable KEEPER; event KeeperRedeemed(address redeemer, uint amount); struct Term { uint percent; // 6 decimals % ( 5000 = 0.5% = 0.005 ) uint claimed; } mapping(address => Term) public terms; mapping(address => address) public walletChange; // uint public totalRedeemable; // uint public redeemableLastUpdated; uint public totalRedeemed; // address public redeemUpdater; constructor( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = IERC20(_KEEPER); // redeemUpdater = _redeemUpdater; // redeemableLastUpdated = block.timestamp; } // function setRedeemUpdater(address _redeemUpdater) external onlyOwner() { // require( _redeemUpdater != address(0) ); // redeemUpdater = _redeemUpdater; // } // Sets terms for a new wallet function setTerms(address _vester, uint _percent ) external onlyOwner() returns ( bool ) { terms[_vester].percent = _percent; return true; } // Sets terms for multiple wallets function setTermsMultiple(address[] calldata _vesters, uint[] calldata _percents ) external onlyOwner() returns ( bool ) { for (uint i=0; i < _vesters.length; i++) { terms[_vesters[i]].percent = _percents[i]; } return true; } // function updateTotalRedeemable() external { // require( msg.sender == redeemUpdater, "Only redeem updater can call." ); // uint keeperBalance = KEEPER.balanceOf( address(this) ); // uint newRedeemable = keeperBalance.add(totalRedeemed).mul(block.timestamp.sub(redeemableLastUpdated)).div(31536000); // totalRedeemable = totalRedeemable.add(newRedeemable); // if (totalRedeemable > keeperBalance ) { // totalRedeemable = keeperBalance; // } // redeemableLastUpdated = block.timestamp; // } // Allows wallet to redeem KEEPER function redeem( uint _amount ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); KEEPER.safeTransfer(msg.sender, _amount); terms[ msg.sender ].claimed = info.claimed.add( _amount ); totalRedeemed = totalRedeemed.add(_amount); emit KeeperRedeemed(msg.sender, _amount); return true; } // Allows wallet owner to transfer rights to a new address function pushWalletChange( address _newWallet ) external returns ( bool ) { require( terms[ msg.sender ].percent != 0 ); walletChange[ msg.sender ] = _newWallet; return true; } // Allows wallet to pull rights from an old address function pullWalletChange( address _oldWallet ) external returns ( bool ) { require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" ); walletChange[ _oldWallet ] = address(0); terms[ msg.sender ] = terms[ _oldWallet ]; delete terms[ _oldWallet ]; return true; } // Amount a wallet can redeem function redeemableFor( address _vester ) public view returns (uint) { return redeemable( terms[ _vester ]); } function redeemable( Term memory _info ) internal view returns ( uint ) { uint maxRedeemable = KEEPER.balanceOf( address(this) ).add( totalRedeemed ); if ( maxRedeemable > 1e17 ) { maxRedeemable = 1e17; } uint maxRedeemableUser = maxRedeemable.mul( _info.percent ).div(1e6); return maxRedeemableUser.sub(_info.claimed); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/Ownable.sol"; interface KeeperCompatibleInterface { function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData); function performUpkeep(bytes calldata performData) external; } interface IStaking { function rebase() external; } interface ITreasury { function auditTotalReserves() external; } interface ISPV { function auditTotalValue() external; } contract DailyUpkeep is KeeperCompatibleInterface, Ownable { /** * Use an interval in seconds and a timestamp to slow execution of Upkeep */ uint public immutable interval; uint public nextTimeStamp; address public staking; address public treasury; address public spv; constructor(address _staking, address _treasury, address _spv, uint _nextTimeStamp, uint _interval) { staking = _staking; treasury = _treasury; spv = _spv; nextTimeStamp = _nextTimeStamp; interval = _interval; } function setStaking(address _staking) external onlyOwner() { staking = _staking; } function setTreasury(address _treasury) external onlyOwner() { treasury = _treasury; } function setSPV(address _spv) external onlyOwner() { spv = _spv; } function checkUpkeep(bytes calldata /* checkData */) external override returns (bool upkeepNeeded, bytes memory /* performData */) { upkeepNeeded = block.timestamp > nextTimeStamp; } function performUpkeep(bytes calldata /* performData */) external override { if (staking != address(0)) { IStaking(staking).rebase(); } if (treasury != address(0)) { ITreasury(treasury).auditTotalReserves(); } if (spv != address(0)) { ISPV(spv).auditTotalValue(); } nextTimeStamp = nextTimeStamp + interval; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; contract VaultOwned is Ownable { address internal _vault; function setVault(address vault_) external onlyOwner() returns (bool) { _vault = vault_; return true; } function vault() public view returns (address) { return _vault; } modifier onlyVault() { require(_vault == msg.sender, "VaultOwned: caller is not the Vault"); _; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract oldMockKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract oldKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external onlyVault() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract iKeeperIndexCalculator is Ownable { using SafeMath for uint; event AssetIndexAdded( uint indexed deposit, uint indexed price, address indexed token ); event IndexUpdated( uint indexed fromIndex, uint indexed toIndex, uint oldPrice, uint newPrice ); event DepositUpdated( uint indexed fromDeposit, uint indexed toDeposit ); event AssetIndexWithdrawn( uint indexed deposit, uint price, uint indexed index, address indexed token ); struct AssetIndex { uint deposit; // In USD uint price; // 6 decimals, in USD uint index; // 9 decimals, starts with 1000000000 address token; // Token address of the asset } AssetIndex[] public indices; uint public netIndex; constructor(uint _netIndex) { require( _netIndex != 0, "Index cannot be 0" ); netIndex = _netIndex; } function calculateIndex() public { uint indexProduct = 0; uint totalDeposit = 0; for (uint i=0; i < indices.length; i++) { uint deposit = indices[i].deposit; totalDeposit = totalDeposit.add(deposit); indexProduct = indexProduct.add( indices[i].index.mul( deposit ) ); } netIndex = indexProduct.div(totalDeposit); } function addAssetIndex(uint _deposit, uint _price, address _token) external onlyOwner() { indices.push( AssetIndex({ deposit: _deposit, price: _price, index: 1e9, token: _token })); } function updateIndex(uint _index, address _token, uint _newPrice) external onlyOwner() { AssetIndex storage assetIndex = indices[ _index ]; require(assetIndex.token == _token, "Wrong index."); uint changeIndex = _newPrice.mul(1e9).div(assetIndex.price); uint fromIndex = assetIndex.index; uint oldPrice = assetIndex.price; assetIndex.index = fromIndex.mul(changeIndex).div(1e9); assetIndex.deposit = assetIndex.deposit.mul(changeIndex).div(1e9); assetIndex.price = _newPrice; emit IndexUpdated(fromIndex, assetIndex.index, oldPrice, _newPrice); } function updateDeposit(uint _index, address _token, uint _amount, bool _add) external onlyOwner() { require(_token == indices[ _index ].token, "Wrong index."); uint oldDeposit = indices[ _index ].deposit; require(_add || oldDeposit >= _amount, "Cannot withdraw more than deposit"); if (!_add) { indices[ _index ].deposit = oldDeposit.sub(_amount); } else { indices[ _index ].deposit = oldDeposit.add(_amount); } emit DepositUpdated(oldDeposit, indices[ _index ].deposit); } function withdrawAsset(uint _index, address _token) external onlyOwner() { AssetIndex memory assetIndex = indices[ _index ]; require(_token == assetIndex.token, "Wrong index."); indices[ _index ] = indices[indices.length-1]; indices.pop(); emit AssetIndexWithdrawn(assetIndex.deposit, assetIndex.price, assetIndex.index, assetIndex.token); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IStaking.sol"; // import "./interfaces/IIndexCalculator.sol"; contract iKEEPER is ERC20, Ownable { using SafeMath for uint; address public immutable TROVE; address public immutable staking; address public indexCalculator; constructor(address _TROVE, address _staking, address _indexCalculator) ERC20("Invest KEEPER", "iKEEPER") { require(_TROVE != address(0)); TROVE = _TROVE; require(_staking != address(0)); staking = _staking; require(_indexCalculator != address(0)); indexCalculator = _indexCalculator; } // function setIndexCalculator( address _indexCalculator ) external onlyOwner() { // require( _indexCalculator != address(0) ); // indexCalculator = _indexCalculator; // } // /** // @notice get iKEEPER index (9 decimals) // @return uint // */ // // function getIndex() public view returns (uint) { // // return IIndexCalculator(indexCalculator).netIndex(); // // } // // /** // // @notice wrap KEEPER // // @param _amount uint // // @return uint // // */ // // function wrapKEEPER( uint _amount ) external returns ( uint ) { // // IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount ); // // uint value = TROVEToiKEEPER( _amount ); // // _mint( msg.sender, value ); // // return value; // // } // /** // @notice wrap TROVE // @param _amount uint // @return uint // */ // function wrap( uint _amount, address _recipient ) external returns ( uint ) { // IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount ); // uint value = TROVEToiKEEPER( _amount ); // _mint( _recipient, value ); // return value; // } // // /** // // @notice unwrap KEEPER // // @param _amount uint // // @return uint // // */ // // function unwrapKEEPER( uint _amount ) external returns ( uint ) { // // _burn( msg.sender, _amount ); // // uint value = iKEEPERToTROVE( _amount ); // // uint keeperBalance = IERC20(KEEPER).balanceOf( address(this) ); // // if (keeperBalance < value ) { // // uint difference = value.sub(keeperBalance); // // require(IsKEEPER(TROVE).balanceOf(address(this)) >= difference, "Contract does not have enough TROVE"); // // IsKEEPER(TROVE).approve(staking, difference); // // IStaking(staking).unstake(difference, false); // // } // // IERC20( KEEPER ).transfer( msg.sender, value ); // // return value; // // } // /** // @notice unwrap TROVE // @param _amount uint // @return uint // */ // function unwrap( uint _amount ) external returns ( uint ) { // _burn( msg.sender, _amount ); // uint value = iKEEPERToTROVE( _amount ); // IsKEEPER( TROVE ).transfer( msg.sender, value ); // return value; // } // /** // @notice converts iKEEPER amount to TROVE // @param _amount uint // @return uint // */ // function iKEEPERToTROVE( uint _amount ) public view returns ( uint ) { // return _amount.mul( getIndex() ).div( 10 ** decimals() ); // } // /** // @notice converts TROVE amount to iKEEPER // @param _amount uint // @return uint // */ // function TROVEToiKEEPER( uint _amount ) public view returns ( uint ) { // return _amount.mul( 10 ** decimals() ).div( getIndex() ); // } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract BondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // intermediate token address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond address public immutable bondCalculator; // calculates value of LP tokens bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference time for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt uint32 vestingTerm; // in seconds } // Info for bond holder struct Bond { uint gonsPayout; // sKEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in seconds) between adjustments uint32 lastTime; // timestamp when last adjustment made } constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) KEEPER */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( KEEPER ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _wrap bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 ); } } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != sKEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IUniswapV2ERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./libraries/FixedPoint.sol"; interface IBondingCalculator { function valuation( address pair_, uint amount_ ) external view returns ( uint _value ); } contract StandardBondingCalculator is IBondingCalculator { using FixedPoint for *; using SafeMath for uint; using SafeMath for uint112; address public immutable KEEPER; constructor( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = a.div(2).add(1); while (b < c) { c = b; b = a.div(b).add(b).div(2); } } else if (a != 0) { c = 1; } } function getKValue( address _pair ) public view returns( uint k_ ) { uint token0 = IERC20Extended( IUniswapV2Pair( _pair ).token0() ).decimals(); uint token1 = IERC20Extended( IUniswapV2Pair( _pair ).token1() ).decimals(); (uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint totalDecimals = token0.add( token1 ); uint pairDecimal = IERC20Extended( _pair ).decimals(); if (totalDecimals < pairDecimal) { uint decimals = pairDecimal.sub(totalDecimals); k_ = reserve0.mul(reserve1).mul(10 ** decimals); } else { uint decimals = totalDecimals.sub(pairDecimal); k_ = reserve0.mul(reserve1).div(10 ** decimals); } } function getTotalValue( address _pair ) public view returns ( uint _value ) { _value = sqrrt(getKValue( _pair )).mul(2); } function valuation( address _pair, uint amount_ ) external view override returns ( uint _value ) { uint totalValue = getTotalValue( _pair ); uint totalSupply = IUniswapV2Pair( _pair ).totalSupply(); _value = totalValue.mul( FixedPoint.fraction( amount_, totalSupply ).decode112with18() ).div( 1e18 ); } function markdown( address _pair ) external view returns ( uint ) { ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint reserve; if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) { reserve = reserve1; } else { reserve = reserve0; } return reserve.mul( 2 * ( 10 ** IERC20Extended( KEEPER ).decimals() ) ).div( getTotalValue( _pair ) ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IUniswapV2ERC20 { function totalSupply() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./IUniswapV2ERC20.sol"; interface IUniswapV2Pair is IUniswapV2ERC20 { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external view returns ( address ); function token1() external view returns ( address ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract aKEEPER is ERC20 { constructor() ERC20("Alpha Keeper", "aKEEPER") { _setupDecimals(9); _mint(msg.sender, 220000000000000); } function burn(uint256 amount) external { _burn(msg.sender, amount); } }
allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO return bool/
function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; }
12,149,779
./full_match/1/0x92FD968AcBd521c232f5fB8c33b342923cC72714/sources/contracts/libs/Stakes.sol
Lock tokens until a lock period pass. stake Staker struct _tokens Amount of tokens to unstake _period Period in blocks that need to pass before withdrawal/
function lockTokens( Stakes.Staker storage stake, uint256 _tokens, uint256 _period ) internal { uint256 lockingPeriod = _period; if (stake.tokensLocked > 0) { lockingPeriod = Math.weightedAverage( stake.tokensLocked, _period, _tokens ); } stake.tokensLocked = stake.tokensLocked.add(_tokens); stake.tokensLockedUntil = block.number.add(lockingPeriod); }
16,482,718
pragma solidity ^0.4.15; contract Victim { // Contract: If the user clears the balance we will pay them 1 eth. uint balance = 100; // pre: balance > 0 function withdraw() public { require(balance > 0); uint transferAmt = 1 ether; // Call the sender's fallback function with 1 eth. // Note that we fail to specify how much gas is available within (). // So, all gas provided by the original caller is available to be consumed. // Contracts do not pay any gas fees in the current version of Ethereum. // But the contract is paying its own eth to the sender. msg.sender.call.value(transferAmt)(""); // clear the balance balance = 0; } // This contract has some eth provided by a caller function() payable external { } }
Call the sender's fallback function with 1 eth. Note that we fail to specify how much gas is available within (). So, all gas provided by the original caller is available to be consumed. Contracts do not pay any gas fees in the current version of Ethereum. But the contract is paying its own eth to the sender. clear the balance
function withdraw() public { require(balance > 0); uint transferAmt = 1 ether; msg.sender.call.value(transferAmt)(""); balance = 0; }
14,089,669
pragma solidity 0.5.6; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import './Condition.sol'; import '../registry/DIDRegistry.sol'; import '../interfaces/ISecretStore.sol'; import '../interfaces/ISecretStorePermission.sol'; import '../agreements/AgreementStoreManager.sol'; /** * @title Access Secret Store Condition * @author Ocean Protocol Team * * @dev Implementation of the Access Secret Store Condition * * Access Secret Store Condition is special condition * where parity secret store can encrypt/decrypt documents * based on the on-chain granted permissions. For a given DID * document, and agreement ID, the owner/provider of the DID * will fulfill the condition. Consequently secret store * will check whether the permission is granted for the consumer * in order to encrypt/decrypt the document. */ contract AccessSecretStoreCondition is Condition, ISecretStore, ISecretStorePermission { struct DocumentPermission { bytes32 agreementIdDeprecated; mapping(address => bool) permission; } mapping(bytes32 => DocumentPermission) private documentPermissions; AgreementStoreManager private agreementStoreManager; event Fulfilled( bytes32 indexed _agreementId, bytes32 indexed _documentId, address indexed _grantee, bytes32 _conditionId ); modifier onlyDIDOwnerOrProvider( bytes32 _documentId ) { DIDRegistry didRegistry = DIDRegistry( agreementStoreManager.getDIDRegistryAddress() ); require( didRegistry.isDIDProvider(_documentId, msg.sender) || msg.sender == didRegistry.getDIDOwner(_documentId), 'Invalid DID owner/provider' ); _; } /** * @notice initialize init the * contract with the following parameters * @dev this function is called only once during the contract * initialization. * @param _owner contract's owner account address * @param _conditionStoreManagerAddress condition store manager address * @param _agreementStoreManagerAddress agreement store manager address */ function initialize( address _owner, address _conditionStoreManagerAddress, address _agreementStoreManagerAddress ) external initializer() { Ownable.initialize(_owner); conditionStoreManager = ConditionStoreManager( _conditionStoreManagerAddress ); agreementStoreManager = AgreementStoreManager( _agreementStoreManagerAddress ); } /** * @notice hashValues generates the hash of condition inputs * with the following parameters * @param _documentId refers to the DID in which secret store will issue the decryption keys * @param _grantee is the address of the granted user or the DID provider * @return bytes32 hash of all these values */ function hashValues( bytes32 _documentId, address _grantee ) public pure returns (bytes32) { return keccak256(abi.encodePacked(_documentId, _grantee)); } /** * @notice fulfill access secret store condition * @dev only DID owner or DID provider can call this * method. Fulfill method sets the permissions * for the granted consumer's address to true then * fulfill the condition * @param _agreementId agreement identifier * @param _documentId refers to the DID in which secret store will issue the decryption keys * @param _grantee is the address of the granted user or the DID provider * @return condition state (Fulfilled/Aborted) */ function fulfill( bytes32 _agreementId, bytes32 _documentId, address _grantee ) public returns (ConditionStoreLibrary.ConditionState) { grantPermission( _grantee, _documentId ); bytes32 _id = generateId( _agreementId, hashValues(_documentId, _grantee) ); ConditionStoreLibrary.ConditionState state = super.fulfill( _id, ConditionStoreLibrary.ConditionState.Fulfilled ); emit Fulfilled( _agreementId, _documentId, _grantee, _id ); return state; } /** * @notice grantPermission is called only by DID owner or provider * @param _grantee is the address of the granted user or the DID provider * @param _documentId refers to the DID in which secret store will issue the decryption keys */ function grantPermission( address _grantee, bytes32 _documentId ) public onlyDIDOwnerOrProvider(_documentId) { documentPermissions[_documentId].permission[_grantee] = true; } /** * @notice renouncePermission is called only by DID owner or provider * @param _grantee is the address of the granted user or the DID provider * @param _documentId refers to the DID in which secret store will issue the decryption keys */ function renouncePermission( address _grantee, bytes32 _documentId ) public onlyDIDOwnerOrProvider(_documentId) { documentPermissions[_documentId].permission[_grantee] = false; } /** * @notice checkPermissions is called by Parity secret store * @param _documentId refers to the DID in which secret store will issue the decryption keys * @param _grantee is the address of the granted user or the DID provider * @return true if the access was granted */ function checkPermissions( address _grantee, bytes32 _documentId ) external view returns(bool permissionGranted) { DIDRegistry didRegistry = DIDRegistry( agreementStoreManager.getDIDRegistryAddress() ); return ( didRegistry.isDIDProvider(_documentId, _grantee) || _grantee == didRegistry.getDIDOwner(_documentId) || documentPermissions[_documentId].permission[_grantee] || didRegistry.getPermission(_documentId, _grantee) ); } }
grantPermission is called only by DID owner or provider _grantee is the address of the granted user or the DID provider _documentId refers to the DID in which secret store will issue the decryption keys/
function grantPermission( address _grantee, bytes32 _documentId ) public onlyDIDOwnerOrProvider(_documentId) { documentPermissions[_documentId].permission[_grantee] = true; }
13,095,174
./full_match/4/0xee7a177EA42C17406E1f3691bE11F90f12a22183/sources/smartcontractkit/documentation/_includes/samples/VRF/VRFD20.sol
Get the current key hash return bytes32/
function keyHash() public view returns (bytes32) { return s_keyHash; }
672,986
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; /* ___ _ _ | _ )_ _ _ _ _ _ _ _ | | | | | _ \ || | ' \| ' \ || | |_| |_| |___/\_,_|_||_|_||_\_, | (_) (_) |__/ * * MIT License * =========== * * Copyright (c) 2020 BunnyFinance * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import {PoolConstant} from "../library/PoolConstant.sol"; import "../interfaces/IPancakePair.sol"; import "../interfaces/IPancakeFactory.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IMasterChef.sol"; import "../interfaces/IBunnyMinter.sol"; import "../zap/ZapBSC.sol"; import "./VaultController.sol"; contract VaultFlipToFlip is VaultController, IStrategy { using SafeBEP20 for IBEP20; using SafeMath for uint256; /* ========== CONSTANTS ============= */ IBEP20 private constant CAKE = IBEP20(0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82); IBEP20 private constant WBNB = IBEP20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); IMasterChef private constant CAKE_MASTER_CHEF = IMasterChef(0x73feaa1eE314F8c655E354234017bE2193C9E24E); PoolConstant.PoolTypes public constant override poolType = PoolConstant.PoolTypes.FlipToFlip; ZapBSC public constant zapBSC = ZapBSC(0xdC2bBB0D33E0e7Dea9F5b98F46EDBaC823586a0C); IPancakeRouter02 private constant ROUTER_V1 = IPancakeRouter02(0x2AD2C5314028897AEcfCF37FD923c079BeEb2C56); IPancakeRouter02 private constant ROUTER_V2 = IPancakeRouter02(0x10ED43C718714eb63d5aA57B78B54704E256024E); IPancakeFactory private constant FACTORY_V1 = IPancakeFactory(0x877Fe7F4e22e21bE397Cd9364fAFd4aF4E15Edb6); uint private constant DUST = 1000; /* ========== STATE VARIABLES ========== */ uint public override pid; address private _token0; address private _token1; uint public totalShares; mapping (address => uint) private _shares; mapping (address => uint) private _principal; mapping (address => uint) private _depositedAt; uint public cakeHarvested; /* ========== MODIFIER ========== */ modifier updateCakeHarvested { uint before = CAKE.balanceOf(address(this)); _; uint _after = CAKE.balanceOf(address(this)); cakeHarvested = cakeHarvested.add(_after).sub(before); } /* ========== INITIALIZER ========== */ function initialize(uint _pid, address _token) external initializer { __VaultController_init(IBEP20(_token)); _stakingToken.safeApprove(address(CAKE_MASTER_CHEF), uint(- 1)); pid = _pid; CAKE.safeApprove(address(zapBSC), uint(- 1)); } /* ========== VIEW FUNCTIONS ========== */ function totalSupply() external view override returns (uint) { return totalShares; } function balance() public view override returns (uint amount) { (amount,) = CAKE_MASTER_CHEF.userInfo(pid, address(this)); } function balanceOf(address account) public view override returns(uint) { if (totalShares == 0) return 0; return balance().mul(sharesOf(account)).div(totalShares); } function withdrawableBalanceOf(address account) public view override returns (uint) { return balanceOf(account); } function sharesOf(address account) public view override returns (uint) { return _shares[account]; } function principalOf(address account) public view override returns (uint) { return _principal[account]; } function earned(address account) public view override returns (uint) { if (balanceOf(account) >= principalOf(account) + DUST) { return balanceOf(account).sub(principalOf(account)); } else { return 0; } } function depositedAt(address account) external view override returns (uint) { return _depositedAt[account]; } function rewardsToken() external view override returns (address) { return address(_stakingToken); } function priceShare() external view override returns(uint) { if (totalShares == 0) return 1e18; return balance().mul(1e18).div(totalShares); } /* ========== MUTATIVE FUNCTIONS ========== */ function deposit(uint _amount) public override { _depositTo(_amount, msg.sender); } function depositAll() external override { deposit(_stakingToken.balanceOf(msg.sender)); } function withdrawAll() external override { uint amount = balanceOf(msg.sender); uint principal = principalOf(msg.sender); uint depositTimestamp = _depositedAt[msg.sender]; totalShares = totalShares.sub(_shares[msg.sender]); delete _shares[msg.sender]; delete _principal[msg.sender]; delete _depositedAt[msg.sender]; amount = _withdrawTokenWithCorrection(amount); uint profit = amount > principal ? amount.sub(principal) : 0; uint withdrawalFee = canMint() ? _minter.withdrawalFee(principal, depositTimestamp) : 0; uint performanceFee = canMint() ? _minter.performanceFee(profit) : 0; if (withdrawalFee.add(performanceFee) > DUST) { _minter.mintForV2(address(_stakingToken), withdrawalFee, performanceFee, msg.sender, depositTimestamp); if (performanceFee > 0) { emit ProfitPaid(msg.sender, profit, performanceFee); } amount = amount.sub(withdrawalFee).sub(performanceFee); } _stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount, withdrawalFee); } function harvest() external override onlyKeeper { _harvest(); uint before = _stakingToken.balanceOf(address(this)); zapBSC.zapInToken(address(CAKE), cakeHarvested, address(_stakingToken)); uint harvested = _stakingToken.balanceOf(address(this)).sub(before); CAKE_MASTER_CHEF.deposit(pid, harvested); emit Harvested(harvested); cakeHarvested = 0; } function _harvest() private updateCakeHarvested { CAKE_MASTER_CHEF.withdraw(pid, 0); } function withdraw(uint shares) external override onlyWhitelisted { uint amount = balance().mul(shares).div(totalShares); totalShares = totalShares.sub(shares); _shares[msg.sender] = _shares[msg.sender].sub(shares); amount = _withdrawTokenWithCorrection(amount); _stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount, 0); } // @dev underlying only + withdrawal fee + no perf fee function withdrawUnderlying(uint _amount) external { uint amount = Math.min(_amount, _principal[msg.sender]); uint shares = Math.min(amount.mul(totalShares).div(balance()), _shares[msg.sender]); totalShares = totalShares.sub(shares); _shares[msg.sender] = _shares[msg.sender].sub(shares); _principal[msg.sender] = _principal[msg.sender].sub(amount); amount = _withdrawTokenWithCorrection(amount); uint depositTimestamp = _depositedAt[msg.sender]; uint withdrawalFee = canMint() ? _minter.withdrawalFee(amount, depositTimestamp) : 0; if (withdrawalFee > DUST) { _minter.mintForV2(address(_stakingToken), withdrawalFee, 0, msg.sender, depositTimestamp); amount = amount.sub(withdrawalFee); } _stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount, withdrawalFee); } // @dev profits only (underlying + bunny) + no withdraw fee + perf fee function getReward() external override { uint amount = earned(msg.sender); uint shares = Math.min(amount.mul(totalShares).div(balance()), _shares[msg.sender]); totalShares = totalShares.sub(shares); _shares[msg.sender] = _shares[msg.sender].sub(shares); _cleanupIfDustShares(); amount = _withdrawTokenWithCorrection(amount); uint depositTimestamp = _depositedAt[msg.sender]; uint performanceFee = canMint() ? _minter.performanceFee(amount) : 0; if (performanceFee > DUST) { _minter.mintForV2(address(_stakingToken), 0, performanceFee, msg.sender, depositTimestamp); amount = amount.sub(performanceFee); } _stakingToken.safeTransfer(msg.sender, amount); emit ProfitPaid(msg.sender, amount, performanceFee); } /* ========== PRIVATE FUNCTIONS ========== */ function _depositTo(uint _amount, address _to) private notPaused updateCakeHarvested { uint _pool = balance(); uint _before = _stakingToken.balanceOf(address(this)); _stakingToken.safeTransferFrom(msg.sender, address(this), _amount); uint _after = _stakingToken.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint shares = 0; if (totalShares == 0) { shares = _amount; } else { shares = (_amount.mul(totalShares)).div(_pool); } totalShares = totalShares.add(shares); _shares[_to] = _shares[_to].add(shares); _principal[_to] = _principal[_to].add(_amount); _depositedAt[_to] = block.timestamp; CAKE_MASTER_CHEF.deposit(pid, _amount); emit Deposited(_to, _amount); } function _withdrawTokenWithCorrection(uint amount) private updateCakeHarvested returns (uint) { uint before = _stakingToken.balanceOf(address(this)); CAKE_MASTER_CHEF.withdraw(pid, amount); return _stakingToken.balanceOf(address(this)).sub(before); } function _cleanupIfDustShares() private { uint shares = _shares[msg.sender]; if (shares > 0 && shares < DUST) { totalShares = totalShares.sub(shares); delete _shares[msg.sender]; } } /* ========== SALVAGE PURPOSE ONLY ========== */ // @dev stakingToken must not remain balance in this contract. So dev should salvage staking token transferred by mistake. function recoverToken(address token, uint amount) external override onlyOwner { if (token == address(CAKE)) { uint cakeBalance = CAKE.balanceOf(address(this)); require(amount <= cakeBalance.sub(cakeHarvested), "VaultFlipToFlip: cannot recover lp's harvested cake"); } IBEP20(token).safeTransfer(owner(), amount); emit Recovered(token, amount); } /* ========== MIGRATE PANCAKE V1 to V2 ========== */ function migrate(address account, uint amount) public { if (amount == 0) return; _depositTo(amount, account); } function migrateToken(uint amount) public onlyOwner { _stakingToken.safeTransferFrom(msg.sender, address(this), amount); CAKE_MASTER_CHEF.deposit(pid, amount); } function setPidToken(uint _pid, address token) external onlyOwner { require(totalShares == 0); pid = _pid; _stakingToken = IBEP20(token); _stakingToken.safeApprove(address(CAKE_MASTER_CHEF), 0); _stakingToken.safeApprove(address(CAKE_MASTER_CHEF), uint(- 1)); _stakingToken.safeApprove(address(_minter), 0); _stakingToken.safeApprove(address(_minter), uint(- 1)); } function approveZap() external onlyOwner { CAKE.safeApprove(address(zapBSC), uint(- 1)); IPancakePair pair = IPancakePair(address(_stakingToken)); address token0 = pair.token0(); address token1 = pair.token1(); _flipOutV1(token0, token1); _flipInV2(token0, token1); _dustInV2(address(_stakingToken), token0, token1); uint lpAmount = IBEP20(_stakingToken).balanceOf(address(this)); CAKE_MASTER_CHEF.deposit(pid, lpAmount); } function _flipOutV1(address token0, address token1) private { address flipV1 = FACTORY_V1.getPair(token0, token1); _approveTokenIfNeededV1(flipV1); uint amount = IBEP20(flipV1).balanceOf(address (this)); ROUTER_V1.removeLiquidity(token0, token1, amount, 0, 0, address(this), block.timestamp); } function _flipInV2(address token0, address token1) private { uint tokenAmount0 = IBEP20(token0).balanceOf(address(this)); uint tokenAmount1 = IBEP20(token1).balanceOf(address(this)); if (token0 == address(CAKE)) { tokenAmount0 = tokenAmount0.sub(cakeHarvested); } if (token1 == address(CAKE)) { tokenAmount1 = tokenAmount1.sub(cakeHarvested); } _approveTokenIfNeededV2(token0); _approveTokenIfNeededV2(token1); ROUTER_V2.addLiquidity(token0, token1, tokenAmount0, tokenAmount1, 0, 0, address(this), block.timestamp); } function _dustInV2(address flipV2, address token0, address token1) private { uint bnbBalance = address(this).balance; if (bnbBalance > DUST) { zapBSC.zapIn{value : bnbBalance}(flipV2); } uint tokenAmount0 = IBEP20(token0).balanceOf(address(this)); if (token0 == address(CAKE)) { tokenAmount0 = tokenAmount0.sub(cakeHarvested); } if (tokenAmount0 > DUST) { if (IBEP20(token0).allowance(address(this), address(zapBSC)) == 0) { IBEP20(token0).safeApprove(address(zapBSC), uint(- 1)); } zapBSC.zapInToken(token0, tokenAmount0, flipV2); } uint tokenAmount1 = IBEP20(token1).balanceOf(address(this)); if (token1 == address(CAKE)) { tokenAmount1 = tokenAmount1.sub(cakeHarvested); } if (tokenAmount1 > DUST) { if (IBEP20(token1).allowance(address(this), address(zapBSC)) == 0) { IBEP20(token1).safeApprove(address(zapBSC), uint(- 1)); } zapBSC.zapInToken(token1, tokenAmount1, flipV2); } } function _approveTokenIfNeededV1(address token) private { if (IBEP20(token).allowance(address(this), address(ROUTER_V1)) == 0) { IBEP20(token).safeApprove(address(ROUTER_V1), uint(- 1)); } } function _approveTokenIfNeededV2(address token) private { if (IBEP20(token).allowance(address(this), address(ROUTER_V2)) == 0) { IBEP20(token).safeApprove(address(ROUTER_V2), uint(- 1)); } } }
profits only (underlying + bunny) + no withdraw fee + perf fee
function getReward() external override { uint amount = earned(msg.sender); uint shares = Math.min(amount.mul(totalShares).div(balance()), _shares[msg.sender]); totalShares = totalShares.sub(shares); _shares[msg.sender] = _shares[msg.sender].sub(shares); _cleanupIfDustShares(); amount = _withdrawTokenWithCorrection(amount); uint depositTimestamp = _depositedAt[msg.sender]; uint performanceFee = canMint() ? _minter.performanceFee(amount) : 0; if (performanceFee > DUST) { _minter.mintForV2(address(_stakingToken), 0, performanceFee, msg.sender, depositTimestamp); amount = amount.sub(performanceFee); } _stakingToken.safeTransfer(msg.sender, amount); emit ProfitPaid(msg.sender, amount, performanceFee); }
6,473,519