file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/11155111/0x3eA9bfbEED417Fd99707387c6d9B4E3d79F54cc2/sources/project:/contracts/UniswapV2Router01.sol
REMOVE LIQUIDITY
function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public override ensure(deadline) returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'MTASwap: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'MTASwap: INSUFFICIENT_B_AMOUNT'); }
3,837,385
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ struct Airline { address airline; bool isRegistered; bool isFunded; uint256 voteCount; uint256 fundingAmount; } struct Flight { address airline; bool isRegistered; uint8 statusCode; string flight; uint256 departureDate; mapping (address => uint256) insuredPassengers; } address private contractOwner; mapping(address => bool) private appContracts; address private appcontractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint256 private constant MIN_ETH = 10 ether; mapping(address => Airline) airlines; mapping(bytes32 => Flight) registeredFlights; mapping(address => uint256) insuredPassengerBalance; mapping(address => uint) voting; uint registeredAirlinesCount; uint airlinesCount; event AirlineRegistered(address airline); event AirlineVoted(uint256 voteCount); event AirlineToVote(address airline); event AirlineVoted(address airline); /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirline ) public { contractOwner = msg.sender; // this.addAirline(firstAirline); // this.registerAirline(firstAirline, msg.sender); Airline memory registerAirline = Airline(firstAirline, false, false, 0, 0); airlines[firstAirline] = registerAirline; airlines[firstAirline].isRegistered = true; registeredAirlinesCount = registeredAirlinesCount.add(1); emit AirlineRegistered(firstAirline); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireAirlineRegistered(address airline) { require(airlines[airline].isRegistered, "Airline Not registered"); _; } modifier requireAirlineFunded(address airline) { require(airlines[airline].isFunded, "Airline Not Funded"); _; } modifier requireAirlineFundedWithMinimumEthers(address airline) { require(airlines[airline].fundingAmount > MIN_ETH , "Minimum 10 ethers are required"); _; } modifier requireFlightRegistered(bytes32 flightKey) { require(registeredFlights[flightKey].isRegistered, "Flight not registered"); _; } modifier requireAppCaller() { require(appContracts[msg.sender], "Caller is not authorized"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function addAirline ( address airlineToRegister ) external requireIsOperational() { Airline memory registerAirline = Airline({ airline : airlineToRegister, isRegistered : true, isFunded : false, voteCount : 0, fundingAmount : 0 }); airlines[airlineToRegister] = registerAirline; airlinesCount = airlinesCount.add(1); } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airlineToRegister, address registeredAirline ) external requireIsOperational() requireAirlineRegistered(registeredAirline) { // require(airlines[airlineToRegister].isRegistered, "Airline is already registered" ); airlines[airlineToRegister].isRegistered = true; registeredAirlinesCount = registeredAirlinesCount.add(1); } function vote ( address airlineToBeAdded ) external requireIsOperational() requireAirlineFunded(msg.sender) { airlines[airlineToBeAdded].voteCount++; voting[airlineToBeAdded]++; emit AirlineToVote(airlineToBeAdded); emit AirlineVoted(msg.sender); emit AirlineVoted(airlines[airlineToBeAdded].voteCount); } function fundAirline ( address airline, uint256 value ) external requireIsOperational() requireAirlineRegistered(airline) { airlines[airline].fundingAmount += value; airlines[airline].isFunded = true; } function registerFlight ( address airline, string _flight, uint256 _departureDate ) external requireAirlineRegistered(airline) requireAirlineFunded(airline) returns(bool) { if(airlines[airline].fundingAmount >= MIN_ETH) { bytes32 flightKey = getFlightKey(airline, _flight, _departureDate); // require(registeredFlights[flightKey] == false, "Flight is already registered"); Flight memory addNewFlight = Flight(airline, true, 0, _flight, _departureDate); registeredFlights[flightKey] = addNewFlight; return true; } else return false; } /** * @dev Buy insurance for a flight * */ function buy ( address _airline, string _flight, uint256 _departureDate, address passenger ) external payable requireIsOperational { // address(this).transfer(msg.value); bytes32 flightKey = getFlightKey(_airline, _flight, _departureDate); registeredFlights[flightKey].insuredPassengers[passenger] = msg.value; } /** * @dev Credits payouts to insurees */ function creditInsurees ( address _airline, string _flight, uint256 _departureDate, address passenger, uint multi ) external requireIsOperational { bytes32 flightKey = getFlightKey(_airline, _flight, _departureDate); insuredPassengerBalance[passenger] = multi.mul(registeredFlights[flightKey].insuredPassengers[passenger]); registeredFlights[flightKey].insuredPassengers[passenger] = 0; } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address insuredPassenger ) external payable requireIsOperational() { require(insuredPassengerBalance[insuredPassenger] > 0, "The insured passenger does not have any balance"); uint256 balance = insuredPassengerBalance[insuredPassenger]; insuredPassenger.transfer(balance); insuredPassengerBalance[insuredPassenger] = 0; } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function getTotalVoteCount ( address airline ) external requireIsOperational() returns(uint) { return(voting[airline]); } function getRegisteredAirlinesCount() external view requireIsOperational returns(uint256) { return registeredAirlinesCount; } function authorizeCaller(address app) external requireContractOwner { appContracts[app] = true; } /** * @dev Add an app contract that can call into this contract */ function deauthorizeCaller(address app) external requireContractOwner { delete appContracts[app]; } function isAirline ( address airline ) external requireIsOperational returns(uint256) { return airlines[airline].fundingAmount; } function isAirlineFunded ( address airline ) external requireIsOperational returns(bool) { return airlines[airline].isFunded; } }
Add an app contract that can call into this contract/
function deauthorizeCaller(address app) external requireContractOwner { delete appContracts[app]; }
5,378,394
pragma solidity 0.4.25; pragma experimental ABIEncoderV2; pragma experimental "v0.5.0"; /** * @title SafeMath * @dev Math operations with safety checks that revert on error * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d17ae0b806b2f8e69b291284bbf30321640609e3/contracts/math/SafeMath.sol */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Convenience and rounding functions when dealing with numbers already factored by 10**18 or 10**27 * @dev Math operations with safety checks that throw on error * https://github.com/dapphub/ds-math/blob/87bef2f67b043819b7195ce6df3058bd3c321107/src/math.sol */ library SafeMathFixedPoint { using SafeMath for uint256; function mul27(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).add(5 * 10**26).div(10**27); } function mul18(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).add(5 * 10**17).div(10**18); } function div18(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(10**18).add(y.div(2)).div(y); } function div27(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(10**27).add(y.div(2)).div(y); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/ERC20Basic.sol */ 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 * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/ERC20.sol */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Claimable.sol */ 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 { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol */ 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 Dai is ERC20 { } contract Weth is ERC20 { function deposit() public payable; function withdraw(uint wad) public; } contract Mkr is ERC20 { } contract Peth is ERC20 { } contract MatchingMarket { function getBuyAmount(ERC20 tokenToBuy, ERC20 tokenToPay, uint256 amountToPay) external view returns(uint256 amountBought); function getPayAmount(ERC20 tokenToPay, ERC20 tokenToBuy, uint amountToBuy) public constant returns (uint amountPaid); function getBestOffer(ERC20 sell_gem, ERC20 buy_gem) public constant returns(uint offerId); function getWorseOffer(uint id) public constant returns(uint offerId); function getOffer(uint id) public constant returns (uint pay_amt, ERC20 pay_gem, uint buy_amt, ERC20 buy_gem); function sellAllAmount(ERC20 pay_gem, uint pay_amt, ERC20 buy_gem, uint min_fill_amount) public returns (uint fill_amt); function buyAllAmount(ERC20 buy_gem, uint buy_amt, ERC20 pay_gem, uint max_fill_amount) public returns (uint fill_amt); } contract DSValue { function read() external view returns(bytes32); } contract Maker { function sai() external view returns(Dai); function gem() external view returns(Weth); function gov() external view returns(Mkr); function skr() external view returns(Peth); function pip() external view returns(DSValue); function pep() external view returns(DSValue); // Join-Exit Spread uint256 public gap; struct Cup { // CDP owner address lad; // Locked collateral (in SKR) uint256 ink; // Outstanding normalised debt (tax only) uint256 art; // Outstanding normalised debt uint256 ire; } uint256 public cupi; mapping (bytes32 => Cup) public cups; function lad(bytes32 cup) public view returns (address); function per() public view returns (uint ray); function tab(bytes32 cup) public returns (uint); function ink(bytes32 cup) public returns (uint); function rap(bytes32 cup) public returns (uint); function chi() public returns (uint); function open() public returns (bytes32 cup); function give(bytes32 cup, address guy) public; function lock(bytes32 cup, uint wad) public; function free(bytes32 cup, uint wad) public; function draw(bytes32 cup, uint wad) public; function join(uint wad) public; function exit(uint wad) public; function wipe(bytes32 cup, uint wad) public; } contract DSProxy { // Technically from DSAuth address public owner; function execute(address _target, bytes _data) public payable returns (bytes32 response); } contract ProxyRegistry { mapping(address => DSProxy) public proxies; function build(address owner) public returns (DSProxy proxy); } contract LiquidLong is Ownable, Claimable, Pausable { using SafeMath for uint256; using SafeMathFixedPoint for uint256; uint256 public providerFeePerEth; MatchingMarket public matchingMarket; Maker public maker; Dai public dai; Weth public weth; Peth public peth; Mkr public mkr; ProxyRegistry public proxyRegistry; struct CDP { uint256 id; uint256 debtInAttodai; uint256 lockedAttoeth; address owner; bool userOwned; } event NewCup(address user, uint256 cup); event CloseCup(address user, uint256 cup); constructor(MatchingMarket _matchingMarket, Maker _maker, ProxyRegistry _proxyRegistry) public payable { providerFeePerEth = 0.01 ether; matchingMarket = _matchingMarket; maker = _maker; dai = maker.sai(); weth = maker.gem(); peth = maker.skr(); mkr = maker.gov(); // MatchingMarket buy/sell dai.approve(address(_matchingMarket), uint256(-1)); weth.approve(address(_matchingMarket), uint256(-1)); // Wipe dai.approve(address(_maker), uint256(-1)); mkr.approve(address(_maker), uint256(-1)); // Join weth.approve(address(_maker), uint256(-1)); // Lock peth.approve(address(_maker), uint256(-1)); proxyRegistry = _proxyRegistry; if (msg.value > 0) { weth.deposit.value(msg.value)(); } } // Receive ETH from WETH withdraw function () external payable { } function wethDeposit() public payable { weth.deposit.value(msg.value)(); } function wethWithdraw(uint256 _amount) public onlyOwner { weth.withdraw(_amount); owner.transfer(_amount); } function attowethBalance() public view returns (uint256 _attoweth) { return weth.balanceOf(address(this)); } function ethWithdraw() public onlyOwner { uint256 _amount = address(this).balance; owner.transfer(_amount); } function transferTokens(ERC20 _token) public onlyOwner { _token.transfer(owner, _token.balanceOf(this)); } function ethPriceInUsd() public view returns (uint256 _attousd) { return uint256(maker.pip().read()); } function estimateDaiSaleProceeds(uint256 _attodaiToSell) public view returns (uint256 _daiPaid, uint256 _wethBought) { return getPayPriceAndAmount(dai, weth, _attodaiToSell); } // buy/pay are from the perspective of the taker/caller (MatchingMarket contracts use buy/pay terminology from perspective of the maker) function getPayPriceAndAmount(ERC20 _payGem, ERC20 _buyGem, uint256 _payDesiredAmount) public view returns (uint256 _paidAmount, uint256 _boughtAmount) { uint256 _offerId = matchingMarket.getBestOffer(_buyGem, _payGem); while (_offerId != 0) { uint256 _payRemaining = _payDesiredAmount.sub(_paidAmount); (uint256 _buyAvailableInOffer, , uint256 _payAvailableInOffer,) = matchingMarket.getOffer(_offerId); if (_payRemaining <= _payAvailableInOffer) { uint256 _buyRemaining = _payRemaining.mul(_buyAvailableInOffer).div(_payAvailableInOffer); _paidAmount = _paidAmount.add(_payRemaining); _boughtAmount = _boughtAmount.add(_buyRemaining); break; } _paidAmount = _paidAmount.add(_payAvailableInOffer); _boughtAmount = _boughtAmount.add(_buyAvailableInOffer); _offerId = matchingMarket.getWorseOffer(_offerId); } return (_paidAmount, _boughtAmount); } function estimateDaiPurchaseCosts(uint256 _attodaiToBuy) public view returns (uint256 _wethPaid, uint256 _daiBought) { return getBuyPriceAndAmount(weth, dai, _attodaiToBuy); } // buy/pay are from the perspective of the taker/caller (MatchingMarket contracts use buy/pay terminology from perspective of the maker) function getBuyPriceAndAmount(ERC20 _payGem, ERC20 _buyGem, uint256 _buyDesiredAmount) public view returns (uint256 _paidAmount, uint256 _boughtAmount) { uint256 _offerId = matchingMarket.getBestOffer(_buyGem, _payGem); while (_offerId != 0) { uint256 _buyRemaining = _buyDesiredAmount.sub(_boughtAmount); (uint256 _buyAvailableInOffer, , uint256 _payAvailableInOffer,) = matchingMarket.getOffer(_offerId); if (_buyRemaining <= _buyAvailableInOffer) { // TODO: verify this logic is correct uint256 _payRemaining = _buyRemaining.mul(_payAvailableInOffer).div(_buyAvailableInOffer); _paidAmount = _paidAmount.add(_payRemaining); _boughtAmount = _boughtAmount.add(_buyRemaining); break; } _paidAmount = _paidAmount.add(_payAvailableInOffer); _boughtAmount = _boughtAmount.add(_buyAvailableInOffer); _offerId = matchingMarket.getWorseOffer(_offerId); } return (_paidAmount, _boughtAmount); } modifier wethBalanceIncreased() { uint256 _startingAttowethBalance = weth.balanceOf(this); _; require(weth.balanceOf(this) > _startingAttowethBalance); } // TODO: change affiliate fee to be 50% of service fee, no parameter needed function openCdp(uint256 _leverage, uint256 _leverageSizeInAttoeth, uint256 _allowedFeeInAttoeth, address _affiliateAddress) public payable wethBalanceIncreased returns (bytes32 _cdpId) { require(_leverage >= 100 && _leverage <= 300); uint256 _lockedInCdpInAttoeth = _leverageSizeInAttoeth.mul(_leverage).div(100); uint256 _loanInAttoeth = _lockedInCdpInAttoeth.sub(_leverageSizeInAttoeth); uint256 _feeInAttoeth = _loanInAttoeth.mul18(providerFeePerEth); require(_feeInAttoeth <= _allowedFeeInAttoeth); uint256 _drawInAttodai = _loanInAttoeth.mul18(uint256(maker.pip().read())); uint256 _attopethLockedInCdp = _lockedInCdpInAttoeth.div27(maker.per()); // Convert all incoming eth to weth (we will pay back later if too much) weth.deposit.value(msg.value)(); // Open CDP _cdpId = maker.open(); // Convert WETH into PETH maker.join(_attopethLockedInCdp); // Store PETH in CDP maker.lock(_cdpId, _attopethLockedInCdp); // This could be 0 if the user has requested a leverage of exactly 100 (1x). // There's no reason to draw 0 dai, try to sell it, or to pay out affiliate // Drawn dai is used to satisfy the _loanInAttoeth. 0 DAI means 0 loan. if (_drawInAttodai > 0) { // Withdraw DAI from CDP maker.draw(_cdpId, _drawInAttodai); // Sell DAI for WETH sellDai(_drawInAttodai, _lockedInCdpInAttoeth, _feeInAttoeth); // Pay provider fee if (_affiliateAddress != address(0)) { // Fee charged is constant. If affiliate provided, split fee with affiliate // Don't bother sending eth to owner, the owner has all weth anyway weth.transfer(_affiliateAddress, _feeInAttoeth.div(2)); } } emit NewCup(msg.sender, uint256(_cdpId)); giveCdpToProxy(msg.sender, _cdpId); } function giveCdpToProxy(address _ownerOfProxy, bytes32 _cdpId) private { DSProxy _proxy = proxyRegistry.proxies(_ownerOfProxy); if (_proxy == DSProxy(0) || _proxy.owner() != _ownerOfProxy) { _proxy = proxyRegistry.build(_ownerOfProxy); } // Send the CDP to the owner's proxy instead of directly to owner maker.give(_cdpId, _proxy); } // extracted function to mitigate stack depth issues function sellDai(uint256 _drawInAttodai, uint256 _lockedInCdpInAttoeth, uint256 _feeInAttoeth) private { uint256 _wethBoughtInAttoweth = matchingMarket.sellAllAmount(dai, _drawInAttodai, weth, 0); // SafeMath failure below catches not enough eth provided uint256 _refundDue = msg.value.add(_wethBoughtInAttoweth).sub(_lockedInCdpInAttoeth).sub(_feeInAttoeth); if (_refundDue > 0) { weth.withdraw(_refundDue); require(msg.sender.call.value(_refundDue)()); } } // closeCdp is intended to be a delegate call that executes as a user's DSProxy function closeCdp(LiquidLong _liquidLong, uint256 _cdpId, uint256 _minimumValueInAttoeth, address _affiliateAddress) external returns (uint256 _payoutOwnerInAttoeth) { address _owner = DSProxy(this).owner(); uint256 _startingAttoethBalance = _owner.balance; // This is delegated, we cannot use storage Maker _maker = _liquidLong.maker(); // if the CDP is already empty, early return (this allows this method to be called off-chain to check estimated payout and not fail for empty CDPs) uint256 _lockedPethInAttopeth = _maker.ink(bytes32(_cdpId)); if (_lockedPethInAttopeth == 0) return 0; _maker.give(bytes32(_cdpId), _liquidLong); _payoutOwnerInAttoeth = _liquidLong.closeGiftedCdp(bytes32(_cdpId), _minimumValueInAttoeth, _owner, _affiliateAddress); require(_maker.lad(bytes32(_cdpId)) == address(this)); require(_owner.balance > _startingAttoethBalance); return _payoutOwnerInAttoeth; } // Close cdp that was just received as part of the same transaction function closeGiftedCdp(bytes32 _cdpId, uint256 _minimumValueInAttoeth, address _recipient, address _affiliateAddress) external wethBalanceIncreased returns (uint256 _payoutOwnerInAttoeth) { require(_recipient != address(0)); uint256 _lockedPethInAttopeth = maker.ink(_cdpId); uint256 _debtInAttodai = maker.tab(_cdpId); // Calculate what we need to claim out of the CDP in Weth uint256 _lockedWethInAttoweth = _lockedPethInAttopeth.div27(maker.per()); // Buy DAI and wipe the entire CDP // Pass in _lockedWethInAttoweth as "max fill amount". If buying DAI costs more in eth than the entire CDP has locked up, revert (we will fail later anyway) uint256 _wethSoldInAttoweth = matchingMarket.buyAllAmount(dai, _debtInAttodai, weth, _lockedWethInAttoweth); uint256 _providerFeeInAttoeth = _wethSoldInAttoweth.mul18(providerFeePerEth); // Calculating governance fee is difficult and gas-intense. Just look up how wiping impacts balance // Then convert that difference into weth, the only asset we charge in. This will require loading up // mkr periodically uint256 _mkrBalanceBeforeInAttomkr = mkr.balanceOf(this); maker.wipe(_cdpId, _debtInAttodai); uint256 _mkrBurnedInAttomkr = _mkrBalanceBeforeInAttomkr.sub(mkr.balanceOf(this)); uint256 _ethValueOfBurnedMkrInAttoeth = _mkrBurnedInAttomkr.mul(uint256(maker.pep().read())) // converts Mkr to DAI .div(uint256(maker.pip().read())); // converts DAI to ETH // Relying on safe-math to revert a situation where LiquidLong would lose weth _payoutOwnerInAttoeth = _lockedWethInAttoweth.sub(_wethSoldInAttoweth).sub(_providerFeeInAttoeth).sub(_ethValueOfBurnedMkrInAttoeth); // Ensure remaining peth in CDP is greater than the value they requested as minimum value require(_payoutOwnerInAttoeth >= _minimumValueInAttoeth); // Pull that value from the CDP, convert it back to WETH for next time // We rely on "free" reverting the transaction if there is not enough peth to profitably close CDP maker.free(_cdpId, _lockedPethInAttopeth); maker.exit(_lockedPethInAttopeth); // DSProxy (or other proxy?) will have issued this request, send it back to the proxy contract. CDP is empty and valueless maker.give(_cdpId, msg.sender); weth.withdraw(_payoutOwnerInAttoeth); if (_affiliateAddress != address(0)) { // Fee charged is constant. If affiliate provided, split fee with affiliate // Don't bother sending eth to owner, the owner has all weth anyway weth.transfer(_affiliateAddress, _providerFeeInAttoeth.div(2)); } require(_recipient.call.value(_payoutOwnerInAttoeth)()); emit CloseCup(msg.sender, uint256(_cdpId)); } // Retrieve CDPs by EFFECTIVE owner, which address owns the DSProxy which owns the CDPs function getCdps(address _owner, uint32 _offset, uint32 _pageSize) public returns (CDP[] _cdps) { // resolve a owner to a proxy, then query by that proxy DSProxy _cdpProxy = proxyRegistry.proxies(_owner); require(_cdpProxy != address(0)); return getCdpsByAddresses(_owner, _cdpProxy, _offset, _pageSize); } // Retrieve CDPs by TRUE owner, as registered in Maker function getCdpsByAddresses(address _owner, address _proxy, uint32 _offset, uint32 _pageSize) public returns (CDP[] _cdps) { _cdps = new CDP[](getCdpCountByOwnerAndProxy(_owner, _proxy, _offset, _pageSize)); uint256 _cdpCount = cdpCount(); uint32 _matchCount = 0; for (uint32 _i = _offset; _i <= _cdpCount && _i < _offset + _pageSize; ++_i) { address _cdpOwner = maker.lad(bytes32(_i)); if (_cdpOwner != _owner && _cdpOwner != _proxy) continue; _cdps[_matchCount] = getCdpDetailsById(_i, _owner); ++_matchCount; } return _cdps; } function cdpCount() public view returns (uint32 _cdpCount) { uint256 count = maker.cupi(); require(count < 2**32); return uint32(count); } function getCdpCountByOwnerAndProxy(address _owner, address _proxy, uint32 _offset, uint32 _pageSize) private view returns (uint32 _count) { uint256 _cdpCount = cdpCount(); _count = 0; for (uint32 _i = _offset; _i <= _cdpCount && _i < _offset + _pageSize; ++_i) { address _cdpOwner = maker.lad(bytes32(_i)); if (_cdpOwner != _owner && _cdpOwner != _proxy) continue; ++_count; } return _count; } function getCdpDetailsById(uint32 _cdpId, address _owner) private returns (CDP _cdp) { (address _cdpOwner, uint256 _collateral,,) = maker.cups(bytes32(_cdpId)); // this one line makes this function not `view`. tab calls chi, which calls drip which mutates state and we can't directly access _chi to bypass this uint256 _debtInAttodai = maker.tab(bytes32(_cdpId)); // Adjust locked attoeth to factor in peth/weth ratio uint256 _lockedAttoeth = (_collateral + 1).mul27(maker.gap().mul18(maker.per())); _cdp = CDP({ id: _cdpId, debtInAttodai: _debtInAttodai, lockedAttoeth: _lockedAttoeth, owner: _cdpOwner, userOwned: _cdpOwner == _owner }); return _cdp; } }
buy/pay are from the perspective of the taker/caller (MatchingMarket contracts use buy/pay terminology from perspective of the maker) TODO: verify this logic is correct
function getBuyPriceAndAmount(ERC20 _payGem, ERC20 _buyGem, uint256 _buyDesiredAmount) public view returns (uint256 _paidAmount, uint256 _boughtAmount) { uint256 _offerId = matchingMarket.getBestOffer(_buyGem, _payGem); while (_offerId != 0) { uint256 _buyRemaining = _buyDesiredAmount.sub(_boughtAmount); (uint256 _buyAvailableInOffer, , uint256 _payAvailableInOffer,) = matchingMarket.getOffer(_offerId); if (_buyRemaining <= _buyAvailableInOffer) { uint256 _payRemaining = _buyRemaining.mul(_payAvailableInOffer).div(_buyAvailableInOffer); _paidAmount = _paidAmount.add(_payRemaining); _boughtAmount = _boughtAmount.add(_buyRemaining); break; } _paidAmount = _paidAmount.add(_payAvailableInOffer); _boughtAmount = _boughtAmount.add(_buyAvailableInOffer); _offerId = matchingMarket.getWorseOffer(_offerId); } return (_paidAmount, _boughtAmount); }
6,411,771
// SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./delegation/DelegationController.sol"; import "./delegation/PartialDifferences.sol"; import "./delegation/TimeHelpers.sol"; import "./delegation/ValidatorService.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function populate() external onlyOwner { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers()); uint currentMonth = timeHelpers.getCurrentMonth(); // clean existing data for ( uint i = _effectiveDelegatedSum.firstUnprocessedMonth; i < _effectiveDelegatedSum.lastChangedMonth.add(1); ++i ) { delete _effectiveDelegatedSum.addDiff[i]; delete _effectiveDelegatedSum.subtractDiff[i]; } delete _effectiveDelegatedSum.value; delete _effectiveDelegatedSum.lastChangedMonth; _effectiveDelegatedSum.firstUnprocessedMonth = currentMonth; uint[] memory validators = validatorService.getTrustedValidators(); for (uint i = 0; i < validators.length; ++i) { uint validatorId = validators[i]; uint currentEffectiveDelegated = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth); uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId); if (effectiveDelegated.length > 0) { assert(currentEffectiveDelegated == effectiveDelegated[0]); } uint added = 0; for (uint j = 0; j < effectiveDelegated.length; ++j) { if (effectiveDelegated[j] != added) { if (effectiveDelegated[j] > added) { _effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j); } else { _effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j); } added = effectiveDelegated[j]; } } delete effectiveDelegated; } } function estimateBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize.add(bountyWasPaidInCurrentEpoch), effectiveDelegated, effectiveDelegatedSum, delegated.div(constantsHolder.msr()), bountyPaidToTheValidator ); return bounty; } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty .mul(effectiveDelegated) .div(effectiveDelegatedSum); return _min( totalBountyShare.div(maxNodesAmount), totalBountyShare.sub(paidToValidator) ); } else { return 0; } } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyOwner { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./utils/StringUtils.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_LAUNCH_LOCKER = "TokenLaunchLocker"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getTokenLaunchLocker() external view returns (address) { return getContract(TOKEN_LAUNCH_LOCKER); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } // SPDX-License-Identifier: AGPL-3.0-only /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Decryption * @dev This contract performs encryption and decryption functions. * Decrypt is used by SkaleDKG contract to decrypt secret key contribution to * validate complaints during the DKG procedure. */ contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; } function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") { _publicKeysInProgress[schainId] = G2Operations.getG2Zero(); } function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]); } function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainId)) { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); } _schainsPublicKeys[schainId] = _publicKeysInProgress[schainId]; delete _publicKeysInProgress[schainId]; } function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainId]; } function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainId].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainId][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainId]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getData() private view returns (BroadcastedData memory) { return _data[keccak256(abi.encodePacked("UnusedFunction"))][0]; } function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) { return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0]; } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; using Strings for uint; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No free Nodes available for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.toString()); string memory dkgRevert = "DKG process did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Schains schains = Schains(contractManager.getContract("Schains")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schains.addSpace(nodeIndex, space); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No free Nodes available for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); waitForNewNode[schainIndex] = true; } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; string domainName; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } modifier onlyNodeOrAdmin(uint nodeIndex) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( isNodeExist(msg.sender, nodeIndex) || _isAdmin(msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(msg.sender), "Sender is not permitted to call this function" ); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, params.domainName, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrAdmin(nodeIndex) { nodes[nodeIndex].domainName = domainName; } /** * @dev Returns nodes with space availability. */ function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return nodes[nodeIndex].domainName; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Returns IPs of active nodes. */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev Returns active nodes linked to the `msg.sender` (validator address). */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeExist(msg.sender, indexOfNodes) && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev Adds node to array. */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, string memory domainName, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId, domainName: domainName })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } /** * @dev Deletes node from array. */ function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainId ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainId, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); _addSchain(msg.sender, 0, schainParameters); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { this.addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Returns the number of Nodes and resource divisor that is needed for a * given Schain type. */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); (partOfNode, numberOfNodes) = schainsInternal.schainTypes(typeOfSchain); if (numberOfNodes == 0) { revert("Bad schain type"); } } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainParameters.typeOfSchain <= schainsInternal.numberOfSchainTypes(), "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainIndexOnNode); delete placeOfSchainOnNode[schainHash][nodeIndex]; } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains */ function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin { schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlyAdmin { delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin { numberOfSchainTypes = newNumberOfSchainTypes; } /** * @dev Allows Admin to move schain to placeOfSchainOnNode map */ function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin { for (uint i = 0; i < schainsGroups[schainHash].length; i++) { uint nodeIndex = schainsGroups[schainHash][i]; for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) { if (schainsForNodes[nodeIndex][j] == schainHash) { placeOfSchainOnNode[schainHash][nodeIndex] = j + 1; } } } } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")); } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev Checks whether sender is a node address from a given schain group. */ function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainId].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 5; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainId; placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { if (placeOfSchainOnNode[schainId][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainId][nodeIndex] - 1; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } /** * @dev Swaps one index for another in an array. */ function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; /** * @title SkaleVerifier * @dev Contains verify function to perform BLS signature verification. */ contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { require(G1Operations.checkRange(signature), "Signature is not valid"); if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB = G1Operations.negate(signature.b); require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { if (counter > 100) { return false; } uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenLaunchLocker.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getTokenLaunchLocker().handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getTokenLaunchLocker() private view returns (TokenLaunchLocker) { return TokenLaunchLocker(contractManager.getTokenLaunchLocker()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; _getTokenLaunchLocker().handleDelegationAdd( delegations[delegationId].holder, delegationId, amount, delegations[delegationId].started ); uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; /** * @title Delegation Period Manager * @dev This contract handles all delegation offerings. Delegations are held for * a specified period (months), and different durations can have different * returns or `stakeMultiplier`. Currently, only delegation periods can be added. */ contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Punisher.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; /** * @title Punisher * @dev This contract handles all slashing and forgiving operations. */ contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenLaunchLocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; import "./PartialDifferences.sol"; /** * @title TokenLaunchLocker * @dev This contract manages lockers applied to the launch process. */ contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; /** * @dev Allows TokenLaunchManager contract to lock an amount of tokens in a * holder wallet. * * Emits a {Locked} event. */ function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new delegations. */ function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new undelegation requests. */ function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev Returns and updates the current delegated amount. */ function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } /** * @dev Adds a delegated amount to the given month. */ function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } /** * @dev Removes a delegated amount from the given month. */ function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } /** * @dev Adds the amount to the total delegated for the given month. */ function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Cannot add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } /** * @dev Unlocks tokens. * * Emits an {Unlocked} event. */ function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } /** * @dev Deletes the delegated amount. */ function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } /** * @dev Deletes the total delegated amount. */ function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } /** * @dev Checks whether total delegated satisfies Proof-of-Use. */ function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenState.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../interfaces/delegation/ILocker.sol"; import "../Permissions.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title Token State * @dev This contract manages lockers to control token transferability. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator `getAndUpdateLockedAmount`. This lock enforces * Proof-of-Use requirements. * * - Tokens that are neither transferable nor delegatable * `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. */ contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface to {SkaleDKG}. */ interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // SPDX-License-Identifier: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } pragma solidity ^0.6.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--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
Allows Schain and NodeRotation contracts to set a Node like exception for a given schain and nodeIndex./
function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; }
401,226
./full_match/137/0x7EDE9CA15267a69E68d76a0595b30bD592177e1e/sources/PawZeesClub.sol
Emergency: can be changed to account for large fluctuations in ETH price
function emergencyChangePrice(uint256 newPrice) public onlyOwner { pawZeesPrice = newPrice; }
4,776,823
./full_match/5/0xb2855d692Dd641357C2710aA659e1d4dcd704dAF/sources/browser/TILYgo.sol
Must Join Previous Level Must be Expired update the amount of dividends per token
function joinTeamPower(uint _level) public returns(uint){ address _userId = msg.sender; uint _cost = SafeMath.div(levelPrice[_level], 2); uint _tokenAmount = calculateTokensReceived(_cost); require(SafeMath.mul(_tokenAmount, 2) <= tokenBalanceLedger_[_userId], 'Low Balance'); if(_level == 1){ require(getUserLevelExpiresAt(_userId, 1) < now); } else if(_level > 1){ for (uint256 l = _level - 1; l > 0; l--) { require( getUserLevelExpiresAt(msg.sender, l) >= now, "Do not skip levels" ); } } tokenBalanceLedger_[_userId] = SafeMath.sub(tokenBalanceLedger_[_userId], _tokenAmount); uint _dividends = SafeMath.div(_cost, sellFee_); if (tokenCirculation_ > 0) { profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenCirculation_); } payoutsTo_[_userId] -= _updatedPayouts; } ==========================================*/
11,598,437
./partial_match/42/0xEE5EE72AE0B2ac03d006085DBA52B0e7B01B90F5/sources/Minter.sol
View function to see pending LOADs on frontend.
function pendingLoad(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accLoadPerShare = pool.accLoadPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 loadReward = multiplier.mul(loadPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accLoadPerShare = accLoadPerShare.add(loadReward.mul(1e12).div(lpSupply)); } } return user.amount.mul(accLoadPerShare).div(1e12).sub(user.rewardDebt); }
3,474,989
pragma solidity ^0.5.17; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract CommitGoodBase { /** * @dev Emiited when a GSN enabled recipient processes a transaction. * @param actualCharge The estimated cost of the transaction. */ event CommitGoodTransactionCharge(uint256 actualCharge); } contract MinterRole is Initializable, Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; function initialize(address sender) public initializer { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } uint256[50] private ______gap; } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is Initializable, ERC20, MinterRole { function initialize(address sender) public initializer { MinterRole.initialize(sender); } /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } uint256[50] private ______gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. 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) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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. * * 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; } uint256[50] private ______gap; } /** * @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens. */ contract ERC20Capped is Initializable, ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function initialize(uint256 cap, address sender) public initializer { ERC20Mintable.initialize(sender); require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20Mintable-mint}. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } uint256[50] private ______gap; } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Initializable, Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { PauserRole.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[50] private ______gap; } /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is Initializable, ERC20, Pausable { function initialize(address sender) public initializer { Pausable.initialize(sender); } 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 increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } uint256[50] private ______gap; } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Base interface for a contract that will be called via the GSN from {IRelayHub}. * * TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead. */ interface IRelayRecipient { /** * @dev Returns the address of the {IRelayHub} instance this recipient interacts with. */ function getHubAddr() external view returns (address); /** * @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the * recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not). * * The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call * calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas, * and the transaction executed with a gas price of at least `gasPrice`. `relay`'s fee is `transactionFee`, and the * recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for * replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature * over all or some of the previous values. * * Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code, * values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions. * * {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered * rejected. A regular revert will also trigger a rejection. */ function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 maxPossibleCharge ) external view returns (uint256, bytes memory); /** * @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g. * pre-charge the sender of the transaction. * * `context` is the second value returned in the tuple by {acceptRelayedCall}. * * Returns a value to be passed to {postRelayedCall}. * * {preRelayedCall} is called with 100k gas: if it runs out during exection or otherwise reverts, the relayed call * will not be executed, but the recipient will still be charged for the transaction's cost. */ function preRelayedCall(bytes calldata context) external returns (bytes32); /** * @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g. * charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform * contract-specific bookkeeping. * * `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of * the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction, * not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value. * * * {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call * and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the * transaction's cost. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external; } /** * @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract * directly. * * See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on * how to deploy an instance of `RelayHub` on your local test network. */ interface IRelayHub { // Relay management /** * @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller * of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay * cannot be its own owner. * * All Ether in this function call will be added to the relay's stake. * Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one. * * Emits a {Staked} event. */ function stake(address relayaddr, uint256 unstakeDelay) external payable; /** * @dev Emitted when a relay's stake or unstakeDelay are increased */ event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay); /** * @dev Registers the caller as a relay. * The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA). * * This function can be called multiple times, emitting new {RelayAdded} events. Note that the received * `transactionFee` is not enforced by {relayCall}. * * Emits a {RelayAdded} event. */ function registerRelay(uint256 transactionFee, string calldata url) external; /** * @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out * {RelayRemoved} events) lets a client discover the list of available relays. */ event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url); /** * @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. * * Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be * callable. * * Emits a {RelayRemoved} event. */ function removeRelayByOwner(address relay) external; /** * @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable. */ event RelayRemoved(address indexed relay, uint256 unstakeTime); /** Deletes the relay from the system, and gives back its stake to the owner. * * Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called. * * Emits an {Unstaked} event. */ function unstake(address relay) external; /** * @dev Emitted when a relay is unstaked for, including the returned stake. */ event Unstaked(address indexed relay, uint256 stake); // States a relay can be in enum RelayState { Unknown, // The relay is unknown to the system: it has never been staked for Staked, // The relay has been staked for, but it is not yet active Registered, // The relay has registered itself, and is active (can relay calls) Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake } /** * @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function * to return an empty entry. */ function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state); // Balance management /** * @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions. * * Unused balance can only be withdrawn by the contract itself, by calling {withdraw}. * * Emits a {Deposited} event. */ function depositFor(address target) external payable; /** * @dev Emitted when {depositFor} is called, including the amount and account that was funded. */ event Deposited(address indexed recipient, address indexed from, uint256 amount); /** * @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue. */ function balanceOf(address target) external view returns (uint256); /** * Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and * contracts can use it to reduce their funding. * * Emits a {Withdrawn} event. */ function withdraw(uint256 amount, address payable dest) external; /** * @dev Emitted when an account withdraws funds from `RelayHub`. */ event Withdrawn(address indexed account, address indexed dest, uint256 amount); // Relaying /** * @dev Checks if the `RelayHub` will accept a relayed operation. * Multiple things must be true for this to happen: * - all arguments must be signed for by the sender (`from`) * - the sender's nonce must be the current one * - the recipient must accept this transaction (via {acceptRelayedCall}) * * Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error * code if it returns one in {acceptRelayedCall}. */ function canRelay( address relay, address from, address to, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata signature, bytes calldata approvalData ) external view returns (uint256 status, bytes memory recipientContext); // Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values. enum PreconditionCheck { OK, // All checks passed, the call can be relayed WrongSignature, // The transaction to relay is not signed by requested sender WrongNonce, // The provided nonce has already been used by the sender AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code } /** * @dev Relays a transaction. * * For this to succeed, multiple conditions must be met: * - {canRelay} must `return PreconditionCheck.OK` * - the sender must be a registered relay * - the transaction's gas price must be larger or equal to the one that was requested by the sender * - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the * recipient) use all gas available to them * - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is * spent) * * If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded * function and {postRelayedCall} will be called in that order. * * Parameters: * - `from`: the client originating the request * - `to`: the target {IRelayRecipient} contract * - `encodedFunction`: the function call to relay, including data * - `transactionFee`: fee (%) the relay takes over actual gas cost * - `gasPrice`: gas price the client is willing to pay * - `gasLimit`: gas to forward when calling the encoded function * - `nonce`: client's nonce * - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses * - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the * `RelayHub`, but it still can be used for e.g. a signature. * * Emits a {TransactionRelayed} event. */ function relayCall( address from, address to, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata signature, bytes calldata approvalData ) external; /** * @dev Emitted when an attempt to relay a call failed. * * This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The * actual relayed call was not executed, and the recipient not charged. * * The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values * over 10 are custom recipient error codes returned from {acceptRelayedCall}. */ event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason); /** * @dev Emitted when a transaction is relayed. * Useful when monitoring a relay's operation and relayed calls to a contract * * Note that the actual encoded function might be reverted: this is indicated in the `status` parameter. * * `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner. */ event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge); // Reason error codes for the TransactionRelayed event enum RelayCallStatus { OK, // The transaction was successfully relayed and execution successful - never included in the event RelayedCallFailed, // The transaction was relayed, but the relayed call failed PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing } /** * @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will * spend up to `relayedCallStipend` gas. */ function requiredGas(uint256 relayedCallStipend) external view returns (uint256); /** * @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee. */ function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256); // Relay penalization. // Any account can penalize relays, removing them from the system immediately, and rewarding the // reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it // still loses half of its stake. /** * @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and * different data (gas price, gas limit, etc. may be different). * * The (unsigned) transaction data and signature for both transactions must be provided. */ function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external; /** * @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}. */ function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external; /** * @dev Emitted when a relay is penalized. */ event Penalized(address indexed relay, address sender, uint256 amount); /** * @dev Returns an account's nonce in `RelayHub`. */ function getNonce(address from) external view returns (uint256); } /** * @dev Base GSN recipient contract: includes the {IRelayRecipient} interface * and enables GSN support on all contracts in the inheritance tree. * * TIP: This contract is abstract. The functions {IRelayRecipient-acceptRelayedCall}, * {_preRelayedCall}, and {_postRelayedCall} are not implemented and must be * provided by derived contracts. See the * xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategies] for more * information on how to use the pre-built {GSNRecipientSignature} and * {GSNRecipientERC20Fee}, or how to write your own. */ contract GSNRecipient is Initializable, IRelayRecipient, Context { function initialize() public initializer { if (_relayHub == address(0)) { setDefaultRelayHub(); } } function setDefaultRelayHub() public { _upgradeRelayHub(0xD216153c06E857cD7f72665E0aF1d7D82172F494); } // Default RelayHub address, deployed on mainnet and all testnets at the same address address private _relayHub; uint256 constant private RELAYED_CALL_ACCEPTED = 0; uint256 constant private RELAYED_CALL_REJECTED = 11; // How much gas is forwarded to postRelayedCall uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000; /** * @dev Emitted when a contract changes its {IRelayHub} contract to a new one. */ event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub); /** * @dev Returns the address of the {IRelayHub} contract for this recipient. */ function getHubAddr() public view returns (address) { return _relayHub; } /** * @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not * use the default instance. * * IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old * {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}. */ function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; } /** * @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If * {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version. */ // This function is view for future-proofing, it may require reading from // storage in the future. function relayHubVersion() public view returns (string memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return "1.0.0"; } /** * @dev Withdraws the recipient's deposits in `RelayHub`. * * Derived contracts should expose this in an external interface with proper access control. */ function _withdrawDeposits(uint256 amount, address payable payee) internal { IRelayHub(_relayHub).withdraw(amount, payee); } // Overrides for Context's functions: when called from RelayHub, sender and // data require some pre-processing: the actual sender is stored at the end // of the call data, which in turns means it needs to be removed from it // when handling said data. /** * @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions, * and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. */ function _msgSender() internal view returns (address payable) { if (msg.sender != _relayHub) { return msg.sender; } else { return _getRelayedCallSender(); } } /** * @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions, * and a reduced version for GSN relayed calls (where msg.data contains additional information). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead. */ function _msgData() internal view returns (bytes memory) { if (msg.sender != _relayHub) { return msg.data; } else { return _getRelayedCallData(); } } // Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the // internal hook. /** * @dev See `IRelayRecipient.preRelayedCall`. * * This function should not be overriden directly, use `_preRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function preRelayedCall(bytes calldata context) external returns (bytes32) { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); return _preRelayedCall(context); } /** * @dev See `IRelayRecipient.preRelayedCall`. * * Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call preprocessing they may wish to do. * */ function _preRelayedCall(bytes memory context) internal returns (bytes32); /** * @dev See `IRelayRecipient.postRelayedCall`. * * This function should not be overriden directly, use `_postRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); } /** * @dev See `IRelayRecipient.postRelayedCall`. * * Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call postprocessing they may wish to do. * */ function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal; /** * @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract * will be charged a fee by RelayHub */ function _approveRelayedCall() internal pure returns (uint256, bytes memory) { return _approveRelayedCall(""); } /** * @dev See `GSNRecipient._approveRelayedCall`. * * This overload forwards `context` to _preRelayedCall and _postRelayedCall. */ function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); } /** * @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged. */ function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_REJECTED + errorCode, ""); } /* * @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's * `serviceFee`. */ function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) { // The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be // charged for 1.4 times the spent amount. return (gas * gasPrice * (100 + serviceFee)) / 100; } function _getRelayedCallSender() private pure returns (address payable result) { // We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array // is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing // so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would // require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20 // bytes. This can always be done due to the 32-byte prefix. // The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the // easiest/most-efficient way to perform this operation. // These fields are not accessible from assembly bytes memory array = msg.data; uint256 index = msg.data.length; // solhint-disable-next-line no-inline-assembly assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function _getRelayedCallData() private pure returns (bytes memory) { // RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data, // we must strip the last 20 bytes (length of an address type) from it. uint256 actualDataLength = msg.data.length - 20; bytes memory actualData = new bytes(actualDataLength); for (uint256 i = 0; i < actualDataLength; ++i) { actualData[i] = msg.data[i]; } return actualData; } } /** * @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. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * 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) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @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)); } } /** * @dev A xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategy] that allows relayed transactions through when they are * accompanied by the signature of a trusted signer. The intent is for this signature to be generated by a server that * performs validations off-chain. Note that nothing is charged to the user in this scheme. Thus, the server should make * sure to account for this in their economic and threat model. */ contract GSNRecipientSignature is Initializable, GSNRecipient { using ECDSA for bytes32; address private _trustedSigner; enum GSNRecipientSignatureErrorCodes { INVALID_SIGNER } /** * @dev Sets the trusted signer that is going to be producing signatures to approve relayed calls. */ function initialize(address trustedSigner) public initializer { require(trustedSigner != address(0), "GSNRecipientSignature: trusted signer is the zero address"); _trustedSigner = trustedSigner; GSNRecipient.initialize(); } /** * @dev Ensures that only transactions with a trusted signature can be relayed through the GSN. */ function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 ) external view returns (uint256, bytes memory) { bytes memory blob = abi.encodePacked( relay, from, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, // Prevents replays on RelayHub getHubAddr(), // Prevents replays in multiple RelayHubs address(this) // Prevents replays in multiple recipients ); if (keccak256(blob).toEthSignedMessageHash().recover(approvalData) == _trustedSigner) { return _approveRelayedCall(); } else { return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_SIGNER)); } } function _preRelayedCall(bytes memory) internal returns (bytes32) { // solhint-disable-previous-line no-empty-blocks } function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal { // solhint-disable-previous-line no-empty-blocks } } /** * @dev Contract that sets access control levels for users and charities. */ contract CommitGoodAccessControl is Initializable, Ownable, GSNRecipientSignature, CommitGoodBase { mapping(address => bool) public users; mapping(address => bool) public campaigns; function initialize(address owner, address trustedSigner) public initializer { GSNRecipientSignature.initialize(trustedSigner); Ownable.initialize(owner); } /** * @dev Emitted when `registrar` has their authorization `enabled`. * @param registrar Address of the account to be authorized or deauthorized. * @param enabled Boolean value that denotes the authorization. */ event Authorize(address indexed registrar, bool enabled); /** * Emitted when `campaign` has their authorization `enabled`. */ event CampaignAuthorize(address indexed campaign, bool enabled); /** * @dev Validates an address * @param account The address that is being validated * * Requirements: * * - `account` cannot be a zero address or a contract address. */ modifier validAddress(address account) { require(account != address(0), "0x0 is not a valid address"); require(!Address.isContract(account), "Contract address is not a valid address"); _; } /** * @dev Validates a contract address * @param kontract The address that is being validated * * Requirements: * * - `kontract` cannot be a zero address and must be a contract address. */ modifier validContract(address kontract) { require(kontract != address(0), "0x0 is not a valid address"); require(Address.isContract(kontract), "Contract address is not a valid address"); _; } /** * @dev Adds a user to the whitelist. * @param account The wallet address of the user. * @return True indicating the function completed successfully. * * Emits a {Authorize} event. * * Requirements: * * - `account` cannot be a zero address and must not be a contract. */ function whitelistUser(address account) public onlyOwner validAddress(account) returns (bool) { users[account] = true; emit Authorize(account, true); return true; } /** * @dev Removes a user from the whitelist. * @param account The wallet address of the user. * @return True indicating the function completed successfully. * * Emits a {Authorize} event. * * Requirements: * * - `account` cannot be a zero address and must not be a contract. */ function blacklistUser(address account) public onlyOwner validAddress(account) returns (bool) { users[account] = false; emit Authorize(account, false); return true; } /** * @dev Adds a campaign from the whitelist. * @param campaign The contract address of the campaign. * @return True indicating the function completed successfully. * * Emits a {CampaignAuthorize} event. * * Requirements: * * - `campaign` cannot be a zero address and must be a contract. */ function whitelistCampaign(address campaign) public onlyOwner validContract(campaign) returns (bool) { campaigns[campaign] = true; emit CampaignAuthorize(campaign, true); return true; } /** * @dev Removes a campaign from the whitelist. * @param campaign The contract address of the campaign. * @return True indicating the function completed successfully. * * Emits a {CampaignAuthorize} event. * * Requirements: * * - `campaign` cannot be a zero address and must be a contract. */ function blacklistCampaign(address campaign) public onlyOwner validContract(campaign) returns (bool) { campaigns[campaign] = false; emit CampaignAuthorize(campaign, false); return true; } /** * @dev Returns a boolean value indicating if the user is whitelisted. * @param account The wallet address of the user. * @return A boolean value indicating if the user is whitelisted. * * Requirements: * * - `account` cannot be a zero address. */ function isUserWhitelisted(address account) public view validAddress(account) returns (bool) { return users[account]; } /** * @dev Returns a boolean value indicating if the campaign is whitelisted. * @param campaign The contract address of the campaign. * @return A boolean value indicating if the campaign is whitelisted. * * Requirements: * * - `campaign` cannot be a zero address and must be a contract. */ function isCampaignWhitelisted(address campaign) public view validContract(campaign) returns (bool) { return campaigns[campaign]; } function _preRelayedCall(bytes memory context) internal returns (bytes32) {} function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal { emit CommitGoodTransactionCharge(actualCharge); } } contract CommitGoodToken is Initializable, Ownable, ERC20, ERC20Detailed, ERC20Mintable, ERC20Capped, ERC20Burnable, ERC20Pausable, CommitGoodBase { CommitGoodAccessControl private _accessControl; function initialize( address owner, string memory name, string memory symbol, uint8 decimals, uint256 capacity) public initializer { Ownable.initialize(owner); ERC20Detailed.initialize(name, symbol, decimals); ERC20Capped.initialize(capacity, owner); ERC20Mintable.initialize(owner); ERC20Pausable.initialize(owner); } /** * @dev Allows the token owner to set the access control contract. In the future when the * organization can become an actual DAO, the owners can utilize a voting mechanism to * update the access control contract. * @param accessControl The address of the access control contract that adheres to the `CommitGoodAccessControl` contract. * * Requirements: * * - `msg.sender` must be the token owner. */ function setAccessControl(CommitGoodAccessControl accessControl) public onlyOwner { _accessControl = accessControl; } /** * @dev Allows the campaigns contract to set approvals on the users behalf when executing donations. * @param donor The donor that executed the transaction. * @param amount The amount that is to be donated to the campaign. * @return A boolean value indicating that the approval succeeded. * * Requirements: * * - `donor` must be whitelisted. * - `_msgSender()` must be a contract and the campaigns contract. */ function campaignApproval(address donor, uint256 amount) public returns(bool) { require(_accessControl.isUserWhitelisted(donor), "The donor must be whitelisted."); require(Address.isContract(_msgSender()), "Recipient must be a contract."); require(_accessControl.isCampaignWhitelisted(_msgSender()), "The campaign must be whitelisted."); _approve(donor, _msgSender(), amount); return true; } }
Adds a user to the whitelist. account The wallet address of the user. return True indicating the function completed successfully. Emits a {Authorize} event. Requirements: - `account` cannot be a zero address and must not be a contract./
function whitelistUser(address account) public onlyOwner validAddress(account) returns (bool) { users[account] = true; emit Authorize(account, true); return true; }
9,925,216
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {FixedPointMath} from "./libraries/FixedPointMath.sol"; import {IMintableERC20} from "./interfaces/IMintableERC20.sol"; import {Pool} from "./libraries/pools/Pool.sol"; import {Stake} from "./libraries/pools/Stake.sol"; import {StakingPools} from "./StakingPools.sol"; import "hardhat/console.sol"; /// @title StakingPools /// @dev A contract which allows users to stake to farm tokens. /// /// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this /// repository: https://github.com/sushiswap/sushiswap. contract StakingPools is ReentrancyGuard { using FixedPointMath for FixedPointMath.uq192x64; using Pool for Pool.Data; using Pool for Pool.List; using SafeERC20 for IERC20; using SafeMath for uint256; using Stake for Stake.Data; event PendingGovernanceUpdated( address pendingGovernance ); event GovernanceUpdated( address governance ); event RewardRateUpdated( uint256 rewardRate ); event PoolRewardWeightUpdated( uint256 indexed poolId, uint256 rewardWeight ); event PoolCreated( uint256 indexed poolId, IERC20 indexed token ); event TokensDeposited( address indexed user, uint256 indexed poolId, uint256 amount ); event TokensWithdrawn( address indexed user, uint256 indexed poolId, uint256 amount ); event TokensClaimed( address indexed user, uint256 indexed poolId, uint256 amount ); /// @dev The token which will be minted as a reward for staking. IMintableERC20 public reward; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; address public pendingGovernance; /// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool /// will return an identifier of zero. mapping(IERC20 => uint256) public tokenPoolIds; /// @dev The context shared between the pools. Pool.Context private _ctx; /// @dev A list of all of the pools. Pool.List private _pools; /// @dev A mapping of all of the user stakes mapped first by pool and then by address. mapping(address => mapping(uint256 => Stake.Data)) private _stakes; constructor( IMintableERC20 _reward, address _governance ) public { require(address(_reward) != address(0), "StakingPools: reward address cannot be 0x0"); require(_governance != address(0), "StakingPools: governance address cannot be 0x0"); reward = _reward; governance = _governance; } /// @dev A modifier which reverts when the caller is not the governance. modifier onlyGovernance() { require(msg.sender == governance, "StakingPools: only governance"); _; } /// @dev Sets the governance. /// /// This function can only called by the current governance. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGovernance { require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } function acceptGovernance() external { require(msg.sender == pendingGovernance, "StakingPools: only pending governance"); governance = pendingGovernance; emit GovernanceUpdated(pendingGovernance); } /// @dev Sets the distribution reward rate. /// /// This will update all of the pools. /// /// @param _rewardRate The number of tokens to distribute per second. function setRewardRate(uint256 _rewardRate) external onlyGovernance { _updatePools(); _ctx.rewardRate = _rewardRate; emit RewardRateUpdated(_rewardRate); } /// @dev Creates a new pool. /// /// The created pool will need to have its reward weight initialized before it begins generating rewards. /// /// @param _token The token the pool will accept for staking. /// /// @return the identifier for the newly created pool. function createPool(IERC20 _token) external onlyGovernance returns (uint256) { require(address(_token) != address(0), "StakingPools: token address cannot be 0x0"); require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool"); uint256 _poolId = _pools.length(); _pools.push(Pool.Data({ token: _token, totalDeposited: 0, rewardWeight: 0, accumulatedRewardWeight: FixedPointMath.uq192x64(0), lastUpdatedBlock: block.number })); tokenPoolIds[_token] = _poolId + 1; emit PoolCreated(_poolId, _token); return _poolId; } /// @dev Sets the reward weights of all of the pools. /// /// @param _rewardWeights The reward weights of all of the pools. function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance { require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch"); _updatePools(); uint256 _totalRewardWeight = _ctx.totalRewardWeight; for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); uint256 _currentRewardWeight = _pool.rewardWeight; if (_currentRewardWeight == _rewardWeights[_poolId]) { continue; } _totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]); _pool.rewardWeight = _rewardWeights[_poolId]; emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]); } _ctx.totalRewardWeight = _totalRewardWeight; } /// @dev Stakes tokens into a pool. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _deposit(_poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); _withdraw(_poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function claim(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); } /// @dev Claims all rewards from a pool and then withdraws all staked tokens. /// /// @param _poolId the pool to exit from. function exit(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); _withdraw(_poolId, _stake.totalDeposited); } /// @dev Gets the rate at which tokens are minted to stakers for all pools. /// /// @return the reward rate. function rewardRate() external view returns (uint256) { return _ctx.rewardRate; } /// @dev Gets the total reward weight between all the pools. /// /// @return the total reward weight. function totalRewardWeight() external view returns (uint256) { return _ctx.totalRewardWeight; } /// @dev Gets the number of pools that exist. /// /// @return the pool count. function poolCount() external view returns (uint256) { return _pools.length(); } /// @dev Gets the token a pool accepts. /// /// @param _poolId the identifier of the pool. /// /// @return the token. function getPoolToken(uint256 _poolId) external view returns (IERC20) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.token; } /// @dev Gets the total amount of funds staked in a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the total amount of staked or deposited tokens. function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.totalDeposited; } /// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward weight. function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.rewardWeight; } /// @dev Gets the amount of tokens per block being distributed to stakers for a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward rate. function getPoolRewardRate(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.getRewardRate(_ctx); } /// @dev Gets the number of tokens a user has staked into a pool. /// /// @param _account The account to query. /// @param _poolId the identifier of the pool. /// /// @return the amount of deposited tokens. function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.totalDeposited; } /// @dev Gets the number of unclaimed reward tokens a user can claim from a pool. /// /// @param _account The account to get the unclaimed balance of. /// @param _poolId The pool to check for unclaimed rewards. /// /// @return the amount of unclaimed reward tokens a user has in a pool. function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx); } /// @dev Updates all of the pools. /// /// Warning: /// Make the staking plan before add a new pool. If the amount of pool becomes too many would /// result the transaction failed due to high gas usage in for-loop. function _updatePools() internal { for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); } } /// @dev Stakes tokens into a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function _deposit(uint256 _poolId, uint256 _depositAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.add(_depositAmount); _stake.totalDeposited = _stake.totalDeposited.add(_depositAmount); _pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount); emit TokensDeposited(msg.sender, _poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount); _stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount); _pool.token.safeTransfer(msg.sender, _withdrawAmount); emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function _claim(uint256 _poolId) internal { Stake.Data storage _stake = _stakes[msg.sender][_poolId]; uint256 _claimAmount = _stake.totalUnclaimed; _stake.totalUnclaimed = 0; reward.mint(msg.sender, _claimAmount); emit TokensClaimed(msg.sender, _poolId, _claimAmount); } } // 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 "../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 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.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; 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: GPL-3.0 pragma solidity 0.6.12; library FixedPointMath { uint256 public constant DECIMALS = 18; uint256 public constant SCALAR = 10**DECIMALS; struct uq192x64 { uint256 x; } function fromU256(uint256 value) internal pure returns (uq192x64 memory) { uint256 x; require(value == 0 || (x = value * SCALAR) / SCALAR == value); return uq192x64(x); } function maximumValue() internal pure returns (uq192x64 memory) { return uq192x64(uint256(-1)); } function add(uq192x64 memory self, uq192x64 memory value) internal pure returns (uq192x64 memory) { uint256 x; require((x = self.x + value.x) >= self.x); return uq192x64(x); } function add(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { return add(self, fromU256(value)); } function sub(uq192x64 memory self, uq192x64 memory value) internal pure returns (uq192x64 memory) { uint256 x; require((x = self.x - value.x) <= self.x); return uq192x64(x); } function sub(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { return sub(self, fromU256(value)); } function mul(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { uint256 x; require(value == 0 || (x = self.x * value) / value == self.x); return uq192x64(x); } function div(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { require(value != 0); return uq192x64(self.x / value); } function cmp(uq192x64 memory self, uq192x64 memory value) internal pure returns (int256) { if (self.x < value.x) { return -1; } if (self.x > value.x) { return 1; } return 0; } function decode(uq192x64 memory self) internal pure returns (uint256) { return self.x / SCALAR; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import {IDetailedERC20} from "./IDetailedERC20.sol"; interface IMintableERC20 is IDetailedERC20{ function mint(address _recipient, uint256 _amount) external; function burnFrom(address account, uint256 amount) external; function lowerHasMinted(uint256 amount)external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import "hardhat/console.sol"; /// @title Pool /// /// @dev A library which provides the Pool data struct and associated functions. library Pool { using FixedPointMath for FixedPointMath.uq192x64; using Pool for Pool.Data; using Pool for Pool.List; using SafeMath for uint256; struct Context { uint256 rewardRate; uint256 totalRewardWeight; } struct Data { IERC20 token; uint256 totalDeposited; uint256 rewardWeight; FixedPointMath.uq192x64 accumulatedRewardWeight; uint256 lastUpdatedBlock; } struct List { Data[] elements; } /// @dev Updates the pool. /// /// @param _ctx the pool context. function update(Data storage _data, Context storage _ctx) internal { _data.accumulatedRewardWeight = _data.getUpdatedAccumulatedRewardWeight(_ctx); _data.lastUpdatedBlock = block.number; } /// @dev Gets the rate at which the pool will distribute rewards to stakers. /// /// @param _ctx the pool context. /// /// @return the reward rate of the pool in tokens per block. function getRewardRate(Data storage _data, Context storage _ctx) internal view returns (uint256) { return _ctx.rewardRate.mul(_data.rewardWeight).div(_ctx.totalRewardWeight); } /// @dev Gets the accumulated reward weight of a pool. /// /// @param _ctx the pool context. /// /// @return the accumulated reward weight. function getUpdatedAccumulatedRewardWeight(Data storage _data, Context storage _ctx) internal view returns (FixedPointMath.uq192x64 memory) { if (_data.totalDeposited == 0) { return _data.accumulatedRewardWeight; } uint256 _elapsedTime = block.number.sub(_data.lastUpdatedBlock); if (_elapsedTime == 0) { return _data.accumulatedRewardWeight; } uint256 _rewardRate = _data.getRewardRate(_ctx); uint256 _distributeAmount = _rewardRate.mul(_elapsedTime); if (_distributeAmount == 0) { return _data.accumulatedRewardWeight; } FixedPointMath.uq192x64 memory _rewardWeight = FixedPointMath.fromU256(_distributeAmount).div(_data.totalDeposited); return _data.accumulatedRewardWeight.add(_rewardWeight); } /// @dev Adds an element to the list. /// /// @param _element the element to add. function push(List storage _self, Data memory _element) internal { _self.elements.push(_element); } /// @dev Gets an element from the list. /// /// @param _index the index in the list. /// /// @return the element at the specified index. function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; } /// @dev Gets the last element in the list. /// /// This function will revert if there are no elements in the list. ///ck /// @return the last element in the list. function last(List storage _self) internal view returns (Data storage) { return _self.elements[_self.lastIndex()]; } /// @dev Gets the index of the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the index of the last element. function lastIndex(List storage _self) internal view returns (uint256) { uint256 _length = _self.length(); return _length.sub(1, "Pool.List: list is empty"); } /// @dev Gets the number of elements in the list. /// /// @return the number of elements. function length(List storage _self) internal view returns (uint256) { return _self.elements.length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import {Pool} from "./Pool.sol"; import "hardhat/console.sol"; /// @title Stake /// /// @dev A library which provides the Stake data struct and associated functions. library Stake { using FixedPointMath for FixedPointMath.uq192x64; using Pool for Pool.Data; using SafeMath for uint256; using Stake for Stake.Data; struct Data { uint256 totalDeposited; uint256 totalUnclaimed; FixedPointMath.uq192x64 lastAccumulatedWeight; } function update(Data storage _self, Pool.Data storage _pool, Pool.Context storage _ctx) internal { _self.totalUnclaimed = _self.getUpdatedTotalUnclaimed(_pool, _ctx); _self.lastAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx); } function getUpdatedTotalUnclaimed(Data storage _self, Pool.Data storage _pool, Pool.Context storage _ctx) internal view returns (uint256) { FixedPointMath.uq192x64 memory _currentAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx); FixedPointMath.uq192x64 memory _lastAccumulatedWeight = _self.lastAccumulatedWeight; if (_currentAccumulatedWeight.cmp(_lastAccumulatedWeight) == 0) { return _self.totalUnclaimed; } uint256 _distributedAmount = _currentAccumulatedWeight .sub(_lastAccumulatedWeight) .mul(_self.totalDeposited) .decode(); return _self.totalUnclaimed.add(_distributedAmount); } } // 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.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: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDetailedERC20 is IERC20 { function name() external returns (string memory); function symbol() external returns (string memory); function decimals() external returns (uint8); } // 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); } }
Creates a new pool. The created pool will need to have its reward weight initialized before it begins generating rewards. _token The token the pool will accept for staking. return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) { require(address(_token) != address(0), "StakingPools: token address cannot be 0x0"); require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool"); uint256 _poolId = _pools.length(); _pools.push(Pool.Data({ token: _token, totalDeposited: 0, rewardWeight: 0, accumulatedRewardWeight: FixedPointMath.uq192x64(0), lastUpdatedBlock: block.number })); tokenPoolIds[_token] = _poolId + 1; emit PoolCreated(_poolId, _token); return _poolId; }
11,710,279
// SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; import { iOVM_L1MultiMessageRelayer } from "../../../iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol"; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title OVM_L1MultiMessageRelayer * @dev The L1 Multi-Message Relayer contract is a gas efficiency optimization which enables the * relayer to submit multiple messages in a single transaction to be relayed by the L1 Cross Domain * Message Sender. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1MultiMessageRelayer is iOVM_L1MultiMessageRelayer, Lib_AddressResolver { /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /********************** * Function Modifiers * **********************/ modifier onlyBatchRelayer() { require( msg.sender == resolve("OVM_L2BatchMessageRelayer"), // solhint-disable-next-line max-line-length "OVM_L1MultiMessageRelayer: Function can only be called by the OVM_L2BatchMessageRelayer" ); _; } /******************** * Public Functions * ********************/ /** * @notice Forwards multiple cross domain messages to the L1 Cross Domain Messenger for relaying * @param _messages An array of L2 to L1 messages */ function batchRelayMessages( L2ToL1Message[] calldata _messages ) override external onlyBatchRelayer { iOVM_L1CrossDomainMessenger messenger = iOVM_L1CrossDomainMessenger( resolve("Proxy__OVM_L1CrossDomainMessenger") ); for (uint256 i = 0; i < _messages.length; i++) { L2ToL1Message memory message = _messages[i]; messenger.relayMessage( message.target, message.sender, message.message, message.messageNonce, message.proof ); } } } // 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 Imports */ import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol"; /** * @title iOVM_L1CrossDomainMessenger */ interface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger { /******************* * Data Structures * *******************/ struct L2MessageInclusionProof { bytes32 stateRoot; Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader; Lib_OVMCodec.ChainInclusionProof stateRootProof; bytes stateTrieWitness; bytes storageTrieWitness; } /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @param _proof Inclusion proof for the given message. */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) external; /** * Replays a cross domain message to the target messenger. * @param _target Target contract address. * @param _sender Original sender address. * @param _message Message to send to the target. * @param _queueIndex CTC Queue index for the message to replay. * @param _gasLimit Gas limit for the provided message. */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _queueIndex, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; interface iOVM_L1MultiMessageRelayer { struct L2ToL1Message { address target; address sender; bytes message; uint256 messageNonce; iOVM_L1CrossDomainMessenger.L2MessageInclusionProof proof; } function batchRelayMessages(L2ToL1Message[] calldata _messages) external; } // 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 { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve( string memory _name ) public view returns ( address ) { return libAddressManager.getAddress(_name); } } // 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"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ 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; } /********************** * Internal Functions * **********************/ /** * 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; pragma experimental ABIEncoderV2; /** * @title iOVM_CrossDomainMessenger */ interface iOVM_CrossDomainMessenger { /********** * Events * **********/ event SentMessage(bytes message); event RelayedMessage(bytes32 msgHash); event FailedRelayedMessage(bytes32 msgHash); /************* * Variables * *************/ function xDomainMessageSender() external view returns (address); /******************** * Public Functions * ********************/ /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes calldata _message, uint32 _gasLimit ) external; } // 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; /** * @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 The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory ) { 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 The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a bytes32 value. * @param _in The bytes32 to encode. * @return _out The RLP encoded bytes32 in bytes. */ function writeBytes32( bytes32 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory ) { 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 RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory ) { 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 RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory ) { 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 The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory ) { 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_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 (_start >= _bytes.length) { 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_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; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string indexed _name, address _newAddress, address _oldAddress ); /************* * Variables * *************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress( string memory _name, address _address ) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet( _name, _address, oldAddress ); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress( string memory _name ) external view returns ( address ) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash( string memory _name ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_name)); } } // 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 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; } }
Flattens a list of byte strings into one byte string. _list List of byte strings to flatten. return The flattened byte string./
function _flatten( bytes[] memory _list ) private pure returns ( bytes memory ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; }
83,264
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/dSTNDV1.sol pragma solidity ^0.8.0; // Staking in sSpell inspired by Chef Nomi's SushiBar - MIT license (originally WTFPL) // modified by BoringCrypto for DictatorDAO contract dSTNDV1 is ERC20("StandardDividend", "dSTND"), AccessControl { using SafeMath for uint256; IERC20 public stnd; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant DEPOSITOR_ROLE = keccak256("DEPOSITOR_ROLE"); constructor(IERC20 _stnd) public { stnd = _stnd; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); } // Enter the bar. Pay some SUSHIs. Earn some shares. function enter(uint256 _amount) public { uint256 totalSTND = stnd.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalSTND == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalSTND); _mint(msg.sender, what); } stnd.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your SUSHIs. function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(stnd.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); stnd.transfer(msg.sender, what); } // Chainbridge functions function mint(address to, uint256 amount) external { // Check that the calling account has the minter role require(hasRole(MINTER_ROLE, msg.sender), "dSTNDV1: Caller is not a minter"); _mint(to, amount); } function burnFrom(address account, uint256 amount) external { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } // Anyswap functions function burn(address account, uint256 amount) external { // Check that the calling account has the minter role require(hasRole(BURNER_ROLE, msg.sender), "dSTNDV1: Caller is not a burner"); _burn(account, amount); } // Polygon functions /** * @notice called when token is deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required amount for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded amount */ function deposit(address user, bytes calldata depositData) external { require(hasRole(DEPOSITOR_ROLE, msg.sender), "dSTNDV1: Caller is not a depositor"); uint256 amount = abi.decode(depositData, (uint256)); _mint(user, amount); } /** * @notice called when user wants to withdraw tokens back to root chain * @dev Should burn user"s tokens. This transaction will be verified when exiting on root chain * @param amount amount of tokens to withdraw */ function withdraw(uint256 amount) external virtual { _burn(_msgSender(), amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
Chainbridge functions Check that the calling account has the minter role
function mint(address to, uint256 amount) external { require(hasRole(MINTER_ROLE, msg.sender), "dSTNDV1: Caller is not a minter"); _mint(to, amount); }
160,998
./full_match/11155111/0x2F0A1cB3DD0D0ADD07961FCEa81741FBb0945299/sources/project_/contracts/Vault.sol
Function to get the amount of tokens generated by depositing the underlying assets _assets List of assets to be deposited/
function previewDeposit(uint256[] memory _assets) public view returns (uint256){ uint256 maxMintable = 0; if(_assets.length != _tokens.length) return maxMintable; maxMintable = _assets[0] / _tokens[0].allocation; for(uint256 i = 1; i < _tokens.length; i++){ if(_assets[i] / _tokens[i].allocation < maxMintable) maxMintable = _assets[i] / _tokens[i].allocation; } return maxMintable; }
3,807,494
pragma solidity >= 0.5.0 <0.7.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } contract IAZTEC { enum ProofCategory { NULL, BALANCED, MINT, BURN, UTILITY } enum NoteStatus { DOES_NOT_EXIST, UNSPENT, SPENT } // proofEpoch = 1 | proofCategory = 1 | proofId = 1 // 1 * 256**(2) + 1 * 256**(1) ++ 1 * 256**(0) uint24 public constant JOIN_SPLIT_PROOF = 65793; // proofEpoch = 1 | proofCategory = 2 | proofId = 1 // (1 * 256**(2)) + (2 * 256**(1)) + (1 * 256**(0)) uint24 public constant MINT_PROOF = 66049; // proofEpoch = 1 | proofCategory = 3 | proofId = 1 // (1 * 256**(2)) + (3 * 256**(1)) + (1 * 256**(0)) uint24 public constant BURN_PROOF = 66305; // proofEpoch = 1 | proofCategory = 4 | proofId = 2 // (1 * 256**(2)) + (4 * 256**(1)) + (2 * 256**(0)) uint24 public constant PRIVATE_RANGE_PROOF = 66562; // proofEpoch = 1 | proofCategory = 4 | proofId = 1 // (1 * 256**(2)) + (4 * 256**(1)) + (2 * 256**(0)) uint24 public constant DIVIDEND_PROOF = 66561; // Hash of a dummy AZTEC note with k = 0 and a = 1 bytes32 public constant ZERO_VALUE_NOTE_HASH = 0xcbc417524e52b95c42a4c42d357938497e3d199eb9b4a0139c92551d4000bc3c; } /** * @title NoteUtils * @author AZTEC * @dev NoteUtils is a utility library that extracts user-readable information from AZTEC proof outputs. * Specifically, `bytes proofOutput` objects can be extracted from `bytes proofOutputs`, * `bytes proofOutput` and `bytes note` can be extracted into their constituent components, **/ library NoteUtils { /** * @dev Get the number of entries in an AZTEC-ABI array (bytes proofOutputs, bytes inputNotes, bytes outputNotes) * All 3 are rolled into a single function to eliminate 'wet' code - the implementations are identical * @param _proofOutputsOrNotes `proofOutputs`, `inputNotes` or `outputNotes` * @return number of entries in the pseudo dynamic array */ function getLength(bytes memory _proofOutputsOrNotes) internal pure returns ( uint len ) { assembly { // first word = the raw byte length // second word = the actual number of entries (hence the 0x20 offset) len := mload(add(_proofOutputsOrNotes, 0x20)) } } /** * @dev Get a bytes object out of a dynamic AZTEC-ABI array * @param _proofOutputsOrNotes `proofOutputs`, `inputNotes` or `outputNotes` * @param _i the desired entry * @return number of entries in the pseudo dynamic array */ function get(bytes memory _proofOutputsOrNotes, uint _i) internal pure returns ( bytes memory out ) { bool valid; assembly { // check that i < the number of entries valid := lt( _i, mload(add(_proofOutputsOrNotes, 0x20)) ) // memory map of the array is as follows: // 0x00 - 0x20 : byte length of array // 0x20 - 0x40 : n, the number of entries // 0x40 - 0x40 + (0x20 * i) : relative memory offset to start of i'th entry (i <= n) // Step 1: compute location of relative memory offset: _proofOutputsOrNotes + 0x40 + (0x20 * i) // Step 2: loaded relative offset and add to _proofOutputsOrNotes to get absolute memory location out := add( mload( add( add(_proofOutputsOrNotes, 0x40), mul(_i, 0x20) ) ), _proofOutputsOrNotes ) } require(valid, "AZTEC array index is out of bounds"); } /** * @dev Extract constituent elements of a `bytes _proofOutput` object * @param _proofOutput an AZTEC proof output * @return inputNotes, AZTEC-ABI dynamic array of input AZTEC notes * @return outputNotes, AZTEC-ABI dynamic array of output AZTEC notes * @return publicOwner, the Ethereum address of the owner of any public tokens involved in the proof * @return publicValue, the amount of public tokens involved in the proof * if (publicValue > 0), this represents a transfer of tokens from ACE to publicOwner * if (publicValue < 0), this represents a transfer of tokens from publicOwner to ACE */ function extractProofOutput(bytes memory _proofOutput) internal pure returns ( bytes memory inputNotes, bytes memory outputNotes, address publicOwner, int256 publicValue ) { assembly { // memory map of a proofOutput: // 0x00 - 0x20 : byte length of proofOutput // 0x20 - 0x40 : relative offset to inputNotes // 0x40 - 0x60 : relative offset to outputNotes // 0x60 - 0x80 : publicOwner // 0x80 - 0xa0 : publicValue // 0xa0 - 0xc0 : challenge inputNotes := add(_proofOutput, mload(add(_proofOutput, 0x20))) outputNotes := add(_proofOutput, mload(add(_proofOutput, 0x40))) publicOwner := and( mload(add(_proofOutput, 0x60)), 0xffffffffffffffffffffffffffffffffffffffff ) publicValue := mload(add(_proofOutput, 0x80)) } } /** * @dev Extract the challenge from a bytes proofOutput variable * @param _proofOutput bytes proofOutput, outputted from a proof validation smart contract * @return bytes32 challenge - cryptographic variable that is part of the sigma protocol */ function extractChallenge(bytes memory _proofOutput) internal pure returns ( bytes32 challenge ) { assembly { challenge := mload(add(_proofOutput, 0xa0)) } } /** * @dev Extract constituent elements of an AZTEC note * @param _note an AZTEC note * @return owner, Ethereum address of note owner * @return noteHash, the hash of the note's public key * @return metadata, note-specific metadata (contains public key and any extra data needed by note owner) */ function extractNote(bytes memory _note) internal pure returns ( address owner, bytes32 noteHash, bytes memory metadata ) { assembly { // memory map of a note: // 0x00 - 0x20 : byte length of note // 0x20 - 0x40 : note type // 0x40 - 0x60 : owner // 0x60 - 0x80 : noteHash // 0x80 - 0xa0 : start of metadata byte array owner := and( mload(add(_note, 0x40)), 0xffffffffffffffffffffffffffffffffffffffff ) noteHash := mload(add(_note, 0x60)) metadata := add(_note, 0x80) } } /** * @dev Get the note type * @param _note an AZTEC note * @return noteType */ function getNoteType(bytes memory _note) internal pure returns ( uint256 noteType ) { assembly { noteType := mload(add(_note, 0x20)) } } } /** * @title Library of proof utility functions * @author AZTEC * Copyright Spilsbury Holdings Ltd 2019. All rights reserved. **/ library ProofUtils { /** * @dev We compress three uint8 numbers into only one uint24 to save gas. * Reverts if the category is not one of [1, 2, 3, 4]. * @param proof The compressed uint24 number. * @return A tuple (uint8, uint8, uint8) representing the epoch, category and proofId. */ function getProofComponents(uint24 proof) internal pure returns (uint8 epoch, uint8 category, uint8 id) { assembly { id := and(proof, 0xff) category := and(div(proof, 0x100), 0xff) epoch := and(div(proof, 0x10000), 0xff) } return (epoch, category, id); } } /** * @title NoteRegistry contract which contains the storage variables that define the set of valid * AZTEC notes for a particular address * @author AZTEC * @dev The NoteRegistry defines the state of valid AZTEC notes. It enacts instructions to update the * state, given to it by the ACE and only the note registry owner can enact a state update. * Copyright Spilsbury Holdings Ltd 2019. All rights reserved. **/ contract NoteRegistry is IAZTEC { using NoteUtils for bytes; using SafeMath for uint256; using ProofUtils for uint24; // registry address is same as ACE address event CreateNoteRegistry( address registryOwner, address registryAddress, uint256 scalingFactor, address linkedTokenAddress, bool canAdjustSupply, bool canConvert ); /** * Note struct. This is the data that we store when we log AZTEC notes inside a NoteRegistry * * Data structured so that the entire struct fits in 1 storage word. * * @notice Yul is used to pack and unpack Note structs in storage for efficiency reasons, * see `NoteRegistry.updateInputNotes` and `NoteRegistry.updateOutputNotes` for more details **/ struct Note { // `status` uses the IAZTEC.NoteStatus enum to track the lifecycle of a note. uint8 status; // `createdOn` logs the timestamp of the block that created this note. There are a few // use cases that require measuring the age of a note, (e.g. interest rate computations). // These lifetime are relevant on timescales of days/months, the 900-ish seconds that a miner // can manipulate a timestamp has little effect, but should be considered when utilizing this parameter. // We store `createdOn` in 5 bytes of data - just in case this contract is still around in 2038 :) // This kicks the 'year 2038' problem down the road by about 400 years uint40 createdOn; // `destroyedOn` logs the timestamp of the block that destroys this note in a transaction. // Default value is 0x0000000000 for notes that have not been spent. uint40 destroyedOn; // The owner of the note address owner; } struct Flags { bool active; bool canAdjustSupply; bool canConvert; } struct Registry { IERC20 linkedToken; uint256 scalingFactor; uint256 totalSupply; bytes32 confidentialTotalMinted; bytes32 confidentialTotalBurned; uint256 supplementTotal; Flags flags; mapping(bytes32 => Note) notes; mapping(address => mapping(bytes32 => uint256)) publicApprovals; } // Every user has their own note registry mapping(address => Registry) internal registries; mapping(bytes32 => bool) public validatedProofs; /** * @dev Call transferFrom on a linked ERC20 token. Used in cases where the ACE's mint * function is called but the token balance of the note registry in question is * insufficient * * @param _value the value to be transferred */ function supplementTokens(uint256 _value) external { Registry storage registry = registries[msg.sender]; require(registry.flags.active == true, "note registry does not exist for the given address"); require(registry.flags.canConvert == true, "note registry does not have conversion rights"); // Only scenario where supplementTokens() should be called is when a mint/burn operation has been executed require(registry.flags.canAdjustSupply == true, "note registry does not have mint and burn rights"); registry.linkedToken.transferFrom(msg.sender, address(this), _value.mul(registry.scalingFactor)); registry.totalSupply = registry.totalSupply.add(_value); } /** * @dev Query the ACE for a previously validated proof * @notice This is a virtual function, that must be overwritten by the contract that inherits from NoteRegistr * * @param _proof - unique identifier for the proof in question and being validated * @param _proofHash - keccak256 hash of a bytes proofOutput argument. Used to identify the proof in question * @param _sender - address of the entity that originally validated the proof * @return boolean - true if the proof has previously been validated, false if not */ function validateProofByHash(uint24 _proof, bytes32 _proofHash, address _sender) public view returns (bool); function createNoteRegistry( address _linkedTokenAddress, uint256 _scalingFactor, bool _canAdjustSupply, bool _canConvert ) public { require(registries[msg.sender].flags.active == false, "address already has a linked note registry"); if (_canConvert) { require(_linkedTokenAddress != address(0x0), "expected the linked token address to exist"); } Registry memory registry = Registry({ linkedToken: IERC20(_linkedTokenAddress), scalingFactor: _scalingFactor, totalSupply: 0, confidentialTotalMinted: ZERO_VALUE_NOTE_HASH, confidentialTotalBurned: ZERO_VALUE_NOTE_HASH, supplementTotal: 0, flags: Flags({ active: true, canAdjustSupply: _canAdjustSupply, canConvert: _canConvert }) }); registries[msg.sender] = registry; emit CreateNoteRegistry( msg.sender, address(this), _scalingFactor, _linkedTokenAddress, _canAdjustSupply, _canConvert ); } /** * @dev Update the state of the note registry according to transfer instructions issued by a * zero-knowledge proof * * @param _proof - unique identifier for a proof * @param _proofOutput - transfer instructions issued by a zero-knowledge proof * @param _proofSender - address of the entity sending the proof */ function updateNoteRegistry( uint24 _proof, bytes memory _proofOutput, address _proofSender ) public { Registry storage registry = registries[msg.sender]; Flags memory flags = registry.flags; require(flags.active == true, "note registry does not exist for the given address"); bytes32 proofHash = keccak256(_proofOutput); require( validateProofByHash(_proof, proofHash, _proofSender) == true, "ACE has not validated a matching proof" ); // clear record of valid proof - stops re-entrancy attacks and saves some gas validatedProofs[proofHash] = false; (bytes memory inputNotes, bytes memory outputNotes, address publicOwner, int256 publicValue) = _proofOutput.extractProofOutput(); updateInputNotes(inputNotes); updateOutputNotes(outputNotes); // If publicValue != 0, enact a token transfer // (publicValue < 0) => transfer from publicOwner to ACE // (publicValue > 0) => transfer from ACE to publicOwner if (publicValue != 0) { require(flags.canConvert == true, "asset cannot be converted into public tokens"); if (publicValue < 0) { uint256 publicApprovals = registry.publicApprovals[publicOwner][proofHash]; registry.totalSupply = registry.totalSupply.add(uint256(-publicValue)); require( publicApprovals >= uint256(-publicValue), "public owner has not validated a transfer of tokens" ); // TODO: redundant step registry.publicApprovals[publicOwner][proofHash] = publicApprovals.sub(uint256(-publicValue)); registry.linkedToken.transferFrom( publicOwner, address(this), uint256(-publicValue).mul(registry.scalingFactor)); } else { registry.totalSupply = registry.totalSupply.sub(uint256(publicValue)); registry.linkedToken.transfer(publicOwner, uint256(publicValue).mul(registry.scalingFactor)); } } } /** * @dev This should be called from an asset contract. */ function publicApprove(address _registryOwner, bytes32 _proofHash, uint256 _value) public { Registry storage registry = registries[_registryOwner]; require(registry.flags.active == true, "note registry does not exist"); registry.publicApprovals[msg.sender][_proofHash] = _value; } /** * @dev Returns the registry for a given address. * * @param _owner - address of the registry owner in question * @return linkedTokenAddress - public ERC20 token that is linked to the NoteRegistry. This is used to * transfer public value into and out of the system * @return scalingFactor - defines how many ERC20 tokens are represented by one AZTEC note * @return totalSupply - TODO * @return confidentialTotalMinted - keccak256 hash of the note representing the total minted supply * @return confidentialTotalBurned - keccak256 hash of the note representing the total burned supply * @return canConvert - flag set by the owner to decide whether the registry has public to private, and * vice versa, conversion privilege * @return canAdjustSupply - determines whether the registry has minting and burning privileges */ function getRegistry(address _owner) public view returns ( address linkedToken, uint256 scalingFactor, uint256 totalSupply, bytes32 confidentialTotalMinted, bytes32 confidentialTotalBurned, bool canConvert, bool canAdjustSupply ) { require(registries[_owner].flags.active == true, "expected registry to be created"); Registry memory registry = registries[_owner]; return ( address(registry.linkedToken), registry.scalingFactor, registry.totalSupply, registry.confidentialTotalMinted, registry.confidentialTotalBurned, registry.flags.canConvert, registry.flags.canAdjustSupply ); } /** * @dev Returns the note for a given address and note hash. * * @param _registryOwner - address of the registry owner * @param _noteHash - keccak256 hash of the note coordiantes (gamma and sigma) * @return status - status of the note, details whether the note is in a note registry * or has been destroyed * @return createdOn - time the note was created * @return destroyedOn - time the note was destroyed * @return noteOwner - address of the note owner */ function getNote(address _registryOwner, bytes32 _noteHash) public view returns ( uint8 status, uint40 createdOn, uint40 destroyedOn, address noteOwner ) { require( registries[_registryOwner].notes[_noteHash].status != uint8(NoteStatus.DOES_NOT_EXIST), "expected note to exist" ); // Load out a note for a given registry owner. Struct unpacking is done in Yul to improve efficiency // solhint-disable-next-line no-unused-vars Note storage notePtr = registries[_registryOwner].notes[_noteHash]; assembly { let note := sload(notePtr_slot) status := and(note, 0xff) createdOn := and(shr(8, note), 0xffffffffff) destroyedOn := and(shr(48, note), 0xffffffffff) noteOwner := and(shr(88, note), 0xffffffffffffffffffffffffffffffffffffffff) } } /** * @dev Removes input notes from the note registry * * @param inputNotes - an array of input notes from a zero-knowledge proof, that are to be * removed and destroyed from a note registry */ function updateInputNotes(bytes memory inputNotes) internal { // set up some temporary variables we'll need // N.B. the status flags are NoteStatus enums, but written as uint8's. // We represent them as uint256 vars because it is the enum values that enforce type safety. // i.e. if we include enums that range beyond 256, // casting to uint8 won't help because we'll still be writing/reading the wrong note status // To summarise the summary - validate enum bounds in tests, use uint256 to save some gas vs uint8 uint256 inputNoteStatusNew = uint256(NoteStatus.SPENT); uint256 inputNoteStatusOld; address inputNoteOwner; // Update the status of each `note` `inputNotes` to the following: // 1. set the note status to SPENT // 2. update the `destroyedOn` timestamp to the current timestamp // We also must check the following: // 1. the note has an existing status of UNSPENT // 2. the note owner matches the provided input uint256 length = inputNotes.getLength(); for (uint256 i = 0; i < length; i += 1) { (address noteOwner, bytes32 noteHash,) = inputNotes.get(i).extractNote(); // Get the storage location of the input note // solhint-disable-next-line no-unused-vars Note storage inputNotePtr = registries[msg.sender].notes[noteHash]; // We update the note using Yul, as Solidity can be a bit inefficient when performing struct packing. // The compiler also invokes redundant sload opcodes that we can remove in Yul assembly { // load up our note from storage let note := sload(inputNotePtr_slot) // extract the status of this note (we'll check that it is UNSPENT outside the asm block) inputNoteStatusOld := and(note, 0xff) // extract the owner of this note (we'll check that it is _owner outside the asm block) inputNoteOwner := and(shr(88, note), 0xffffffffffffffffffffffffffffffffffffffff) // update the input note and write it into storage. // We need to change its `status` from UNSPENT to SPENT, and update `destroyedOn` sstore( inputNotePtr_slot, or( // zero out the bits used to store `status` and `destroyedOn` // `status` occupies byte index 1, `destroyedOn` occupies byte indices 6 - 11. // We create bit mask with a NOT opcode to reduce contract bytecode size. // We then perform logical AND with the bit mask to zero out relevant bits and( note, not(0xffffffffff0000000000ff) ), // Now that we have zeroed out storage locations of `status` and `destroyedOn`, update them or( // Create 5-byte timestamp and shift into byte positions 6-11 with a bit shift shl(48, and(timestamp, 0xffffffffff)), // Combine with the new note status (masked to a uint8) and(inputNoteStatusNew, 0xff) ) ) ) } // Check that the note status is UNSPENT require(inputNoteStatusOld == uint256(NoteStatus.UNSPENT), "input note status is not UNSPENT"); // Check that the note owner is the expected owner require(inputNoteOwner == noteOwner, "input note owner does not match"); } } /** * @dev Adds output notes to the note registry * * @param outputNotes - an array of output notes from a zero-knowledge proof, that are to be * added to the note registry */ function updateOutputNotes(bytes memory outputNotes) internal { // set up some temporary variables we'll need uint256 outputNoteStatusNew = uint256(NoteStatus.UNSPENT); uint256 outputNoteStatusOld; uint256 length = outputNotes.getLength(); for (uint256 i = 0; i < length; i += 1) { (address noteOwner, bytes32 noteHash,) = outputNotes.get(i).extractNote(); require(noteOwner != address(0x0), "output note owner cannot be address(0x0)"); // Create a record in the note registry for this output note // solhint-disable-next-line no-unused-vars Note storage outputNotePtr = registries[msg.sender].notes[noteHash]; // We manually pack our note struct in Yul, because Solidity can be a bit liberal with gas when doing this assembly { // Load the status flag for this note - we check this equals DOES_NOT_EXIST outside asm block outputNoteStatusOld := and(sload(outputNotePtr_slot), 0xff) // Write a new note into storage sstore( outputNotePtr_slot, // combine `status`, `createdOn` and `owner` via logical OR opcodes or( or( // `status` occupies byte position 0 and(outputNoteStatusNew, 0xff), // mask to 1 byte (uint8) // `createdOn` occupies byte positions 1-5 => shift by 8 bits shl(8, and(timestamp, 0xffffffffff)) // mask timestamp to 40 bits ), // `owner` occupies byte positions 11-31 => shift by 88 bits shl(88, noteOwner) // noteOwner already of address type, no need to mask ) ) } require(outputNoteStatusOld == uint256(NoteStatus.DOES_NOT_EXIST), "output note exists"); } } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Library of SafeMath arithmetic operations * @author AZTEC * Copyright Spilsbury Holdings Ltd 2019. All rights reserved. **/ library SafeMath8 { /** * @dev SafeMath multiplication * @param a - uint8 multiplier * @param b - uint8 multiplicand * @return uint8 result of multiplying a and b */ function mul(uint8 a, uint8 b) internal pure returns (uint8) { uint256 c = uint256(a) * uint256(b); require(c < 256, "uint8 mul triggered integer overflow"); return uint8(c); } /** * @dev SafeMath division * @param a - uint8 dividend * @param b - uint8 divisor * @return uint8 result of dividing a by b */ function div(uint8 a, uint8 b) internal pure returns (uint8) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // assert(a == b * c + a % b); // There is no case in which this doesn’t hold return a / b; } /** * @dev SafeMath subtraction * @param a - uint8 minuend * @param b - uint8 subtrahend * @return uint8 result of subtracting b from a */ function sub(uint8 a, uint8 b) internal pure returns (uint8) { require(b <= a, "uint8 sub triggered integer underflow"); return a - b; } /** * @dev SafeMath addition * @param a - uint8 addend * @param b - uint8 addend * @return uint8 result of adding a and b */ function add(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a + b; require(c >= a, "uint8 add triggered integer overflow"); return c; } } /** * @title The AZTEC Cryptography Engine * @author AZTEC * @dev ACE validates the AZTEC protocol's family of zero-knowledge proofs, which enables * digital asset builders to construct fungible confidential digital assets according to the AZTEC token standard. * Copyright Spilsbury Holdings Ltd 2019. All rights reserved. **/ contract ACE is IAZTEC, Ownable, NoteRegistry { using NoteUtils for bytes; using ProofUtils for uint24; using SafeMath for uint256; using SafeMath8 for uint8; // keccak256 hash of "JoinSplitSignature(uint24 proof,bytes32 noteHash,uint256 challenge,address sender)" bytes32 constant internal JOIN_SPLIT_SIGNATURE_TYPE_HASH = 0xf671f176821d4c6f81e66f9704cdf2c5c12d34bd23561179229c9fe7a9e85462; event SetCommonReferenceString(bytes32[6] _commonReferenceString); event SetProof( uint8 indexed epoch, uint8 indexed category, uint8 indexed id, address validatorAddress ); event IncrementLatestEpoch(uint8 newLatestEpoch); // The commonReferenceString contains one G1 group element and one G2 group element, // that are created via the AZTEC protocol's trusted setup. All zero-knowledge proofs supported // by ACE use the same common reference string. bytes32[6] private commonReferenceString; // `validators`contains the addresses of the contracts that validate specific proof types address[0x100][0x100][0x10000] public validators; // a list of invalidated proof ids, used to blacklist proofs in the case of a vulnerability being discovered bool[0x100][0x100][0x10000] public disabledValidators; // latest proof epoch accepted by this contract uint8 public latestEpoch = 1; // keep track of validated balanced proofs mapping(bytes32 => bool) public validatedProofs; /** * @dev contract constructor. Sets the owner of ACE **/ constructor() public Ownable() {} /** * @dev Mint AZTEC notes * * @param _proof the AZTEC proof object * @param _proofData the mint proof construction data * @param _proofSender the Ethereum address of the original transaction sender. It is explicitly assumed that * an asset using ACE supplies this field correctly - if they don't their asset is vulnerable to front-running * Unnamed param is the AZTEC zero-knowledge proof data * @return two `bytes` objects. The first contains the new confidentialTotalSupply note and the second contains the * notes that were created. Returned so that a zkAsset can emit the appropriate events */ function mint( uint24 _proof, bytes calldata _proofData, address _proofSender ) external returns (bytes memory) { Registry storage registry = registries[msg.sender]; require(registry.flags.active == true, "note registry does not exist for the given address"); require(registry.flags.canAdjustSupply == true, "this asset is not mintable"); // Check that it's a mintable proof (, uint8 category, ) = _proof.getProofComponents(); require(category == uint8(ProofCategory.MINT), "this is not a mint proof"); bytes memory _proofOutputs = this.validateProof(_proof, _proofSender, _proofData); require(_proofOutputs.getLength() > 0, "call to validateProof failed"); // Dealing with notes representing totals (bytes memory oldTotal, // inputNotesTotal bytes memory newTotal, // outputNotesTotal , ) = _proofOutputs.get(0).extractProofOutput(); // Check the previous confidentialTotalSupply, and then assign the new one (, bytes32 oldTotalNoteHash, ) = oldTotal.get(0).extractNote(); require(oldTotalNoteHash == registry.confidentialTotalMinted, "provided total minted note does not match"); (, bytes32 newTotalNoteHash, ) = newTotal.get(0).extractNote(); registry.confidentialTotalMinted = newTotalNoteHash; // Dealing with minted notes (, bytes memory mintedNotes, // output notes , ) = _proofOutputs.get(1).extractProofOutput(); updateOutputNotes(mintedNotes); return(_proofOutputs); } /** * @dev Burn AZTEC notes * * @param _proof the AZTEC proof object * @param _proofData the burn proof construction data * @param _proofSender the Ethereum address of the original transaction sender. It is explicitly assumed that * an asset using ACE supplies this field correctly - if they don't their asset is vulnerable to front-running * Unnamed param is the AZTEC zero-knowledge proof data * @return two `bytes` objects. The first contains the new confidentialTotalSupply note and the second contains the * notes that were created. Returned so that a zkAsset can emit the appropriate events */ function burn( uint24 _proof, bytes calldata _proofData, address _proofSender ) external returns (bytes memory) { Registry storage registry = registries[msg.sender]; require(registry.flags.active == true, "note registry does not exist for the given address"); require(registry.flags.canAdjustSupply == true, "this asset is not burnable"); // Check that it's a burnable proof (, uint8 category, ) = _proof.getProofComponents(); require(category == uint8(ProofCategory.BURN), "this is not a burn proof"); bytes memory _proofOutputs = this.validateProof(_proof, _proofSender, _proofData); // Dealing with notes representing totals (bytes memory oldTotal, // input notes bytes memory newTotal, // output notes , ) = _proofOutputs.get(0).extractProofOutput(); (, bytes32 oldTotalNoteHash, ) = oldTotal.get(0).extractNote(); require(oldTotalNoteHash == registry.confidentialTotalBurned, "provided total burned note does not match"); (, bytes32 newTotalNoteHash, ) = newTotal.get(0).extractNote(); registry.confidentialTotalBurned = newTotalNoteHash; // Dealing with burned notes (, bytes memory burnedNotes, ,) = _proofOutputs.get(1).extractProofOutput(); // Although they are outputNotes, they are due to be destroyed - need removing from the note registry updateInputNotes(burnedNotes); return(_proofOutputs); } /** * @dev Validate an AZTEC zero-knowledge proof. ACE will issue a validation transaction to the smart contract * linked to `_proof`. The validator smart contract will have the following interface: * * function validate( * bytes _proofData, * address _sender, * bytes32[6] _commonReferenceString * ) public returns (bytes) * * @param _proof the AZTEC proof object * @param _sender the Ethereum address of the original transaction sender. It is explicitly assumed that * an asset using ACE supplies this field correctly - if they don't their asset is vulnerable to front-running * Unnamed param is the AZTEC zero-knowledge proof data * @return a `bytes proofOutputs` variable formatted according to the Cryptography Engine standard */ function validateProof(uint24 _proof, address _sender, bytes calldata) external returns (bytes memory) { require(_proof != 0, "expected the proof to be valid"); // validate that the provided _proof object maps to a corresponding validator and also that // the validator is not disabled address validatorAddress = getValidatorAddress(_proof); bytes memory proofOutputs; assembly { // the first evm word of the 3rd function param is the abi encoded location of proof data let proofDataLocation := add(0x04, calldataload(0x44)) // manually construct validator calldata map let memPtr := mload(0x40) mstore(add(memPtr, 0x04), 0x100) // location in calldata of the start of `bytes _proofData` (0x100) mstore(add(memPtr, 0x24), _sender) mstore(add(memPtr, 0x44), sload(commonReferenceString_slot)) mstore(add(memPtr, 0x64), sload(add(0x01, commonReferenceString_slot))) mstore(add(memPtr, 0x84), sload(add(0x02, commonReferenceString_slot))) mstore(add(memPtr, 0xa4), sload(add(0x03, commonReferenceString_slot))) mstore(add(memPtr, 0xc4), sload(add(0x04, commonReferenceString_slot))) mstore(add(memPtr, 0xe4), sload(add(0x05, commonReferenceString_slot))) // 0x104 because there's an address, the length 6 and the static array items let destination := add(memPtr, 0x104) // note that we offset by 0x20 because the first word is the length of the dynamic bytes array let proofDataSize := add(calldataload(proofDataLocation), 0x20) // copy the calldata into memory so we can call the validator contract calldatacopy(destination, proofDataLocation, proofDataSize) // call our validator smart contract, and validate the call succeeded let callSize := add(proofDataSize, 0x104) switch staticcall(gas, validatorAddress, memPtr, callSize, 0x00, 0x00) case 0 { mstore(0x00, 400) revert(0x00, 0x20) // call failed because proof is invalid } // copy returndata to memory returndatacopy(memPtr, 0x00, returndatasize) // store the proof outputs in memory mstore(0x40, add(memPtr, returndatasize)) // the first evm word in the memory pointer is the abi encoded location of the actual returned data proofOutputs := add(memPtr, mload(memPtr)) } // if this proof satisfies a balancing relationship, we need to record the proof hash if (((_proof >> 8) & 0xff) == uint8(ProofCategory.BALANCED)) { uint256 length = proofOutputs.getLength(); for (uint256 i = 0; i < length; i += 1) { bytes32 proofHash = keccak256(proofOutputs.get(i)); bytes32 validatedProofHash = keccak256(abi.encode(proofHash, _proof, msg.sender)); validatedProofs[validatedProofHash] = true; } } return proofOutputs; } /** * @dev Clear storage variables set when validating zero-knowledge proofs. * The only address that can clear data from `validatedProofs` is the address that created the proof. * Function is designed to utilize [EIP-1283](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1283.md) * to reduce gas costs. It is highly likely that any storage variables set by `validateProof` * are only required for the duration of a single transaction. * E.g. a decentralized exchange validating a swap proof and sending transfer instructions to * two confidential assets. * This method allows the calling smart contract to recover most of the gas spent by setting `validatedProofs` * @param _proof the AZTEC proof object * @param _proofHashes dynamic array of proof hashes */ function clearProofByHashes(uint24 _proof, bytes32[] calldata _proofHashes) external { uint256 length = _proofHashes.length; for (uint256 i = 0; i < length; i += 1) { bytes32 proofHash = _proofHashes[i]; require(proofHash != bytes32(0x0), "expected no empty proof hash"); bytes32 validatedProofHash = keccak256(abi.encode(proofHash, _proof, msg.sender)); require(validatedProofs[validatedProofHash] == true, "can only clear previously validated proofs"); validatedProofs[validatedProofHash] = false; } } /** * @dev Set the common reference string. * If the trusted setup is re-run, we will need to be able to change the crs * @param _commonReferenceString the new commonReferenceString */ function setCommonReferenceString(bytes32[6] memory _commonReferenceString) public { require(isOwner(), "only the owner can set the common reference string"); commonReferenceString = _commonReferenceString; emit SetCommonReferenceString(_commonReferenceString); } /** * @dev Forever invalidate the given proof. * @param _proof the AZTEC proof object */ function invalidateProof(uint24 _proof) public { require(isOwner(), "only the owner can invalidate a proof"); (uint8 epoch, uint8 category, uint8 id) = _proof.getProofComponents(); require(validators[epoch][category][id] != address(0x0), "can only invalidate proofs that exist"); disabledValidators[epoch][category][id] = true; } /** * @dev Validate a previously validated AZTEC proof via its hash * This enables confidential assets to receive transfer instructions from a dApp that * has already validated an AZTEC proof that satisfies a balancing relationship. * @param _proof the AZTEC proof object * @param _proofHash the hash of the `proofOutput` received by the asset * @param _sender the Ethereum address of the contract issuing the transfer instruction * @return a boolean that signifies whether the corresponding AZTEC proof has been validated */ function validateProofByHash( uint24 _proof, bytes32 _proofHash, address _sender ) public view returns (bool) { // We need create a unique encoding of _proof, _proofHash and _sender, // and use as a key to access validatedProofs // We do this by computing bytes32 validatedProofHash = keccak256(ABI.encode(_proof, _proofHash, _sender)) // We also need to access disabledValidators[_proof.epoch][_proof.category][_proof.id] // This bit is implemented in Yul, as 3-dimensional array access chews through // a lot of gas in Solidity, as does ABI.encode bytes32 validatedProofHash; bool isValidatorDisabled; assembly { // inside _proof, we have 3 packed variables : [epoch, category, id] // each is a uint8. // We need to compute the storage key for `disabledValidators[epoch][category][id]` // Type of array is bool[0x100][0x100][0x100] // Solidity will only squish 32 boolean variables into a single storage slot, not 256 // => result of disabledValidators[epoch][category] is stored in 0x08 storage slots // => result of disabledValidators[epoch] is stored in 0x08 * 0x100 = 0x800 storage slots // To compute the storage slot disabledValidators[epoch][category][id], we do the following: // 1. get the disabledValidators slot // 2. add (epoch * 0x800) to the slot (or epoch << 11) // 3. add (category * 0x08) to the slot (or category << 3) // 4. add (id / 0x20) to the slot (or id >> 5) // Once the storage slot has been loaded, we need to isolate the byte that contains our boolean // This will be equal to id % 0x20, which is also id & 0x1f // Putting this all together. The storage slot offset from '_proof' is... // epoch: ((_proof & 0xff0000) >> 16) << 11 = ((_proof & 0xff0000) >> 5) // category: ((_proof & 0xff00) >> 8) << 3 = ((_proof & 0xff00) >> 5) // id: (_proof & 0xff) >> 5 // i.e. the storage slot offset = _proof >> 5 // the byte index of the storage word that we require, is equal to (_proof & 0x1f) // to convert to a bit index, we multiply by 8 // i.e. bit index = shl(3, and(_proof & 0x1f)) // => result = shr(shl(3, and_proof & 0x1f), value) isValidatorDisabled := shr( shl( 0x03, and(_proof, 0x1f) ), sload(add(shr(5, _proof), disabledValidators_slot)) ) // Next, compute validatedProofHash = keccak256(abi.encode(_proofHash, _proof, _sender)) // cache free memory pointer - we will overwrite it when computing hash (cheaper than using free memory) let memPtr := mload(0x40) mstore(0x00, _proofHash) mstore(0x20, _proof) mstore(0x40, _sender) validatedProofHash := keccak256(0x00, 0x60) mstore(0x40, memPtr) // restore the free memory pointer } require(isValidatorDisabled == false, "proof id has been invalidated"); return validatedProofs[validatedProofHash]; } /** * @dev Adds or modifies a proof into the Cryptography Engine. * This method links a given `_proof` to a smart contract validator. * @param _proof the AZTEC proof object * @param _validatorAddress the address of the smart contract validator */ function setProof( uint24 _proof, address _validatorAddress ) public { require(isOwner(), "only the owner can set a proof"); require(_validatorAddress != address(0x0), "expected the validator address to exist"); (uint8 epoch, uint8 category, uint8 id) = _proof.getProofComponents(); require(epoch <= latestEpoch, "the proof epoch cannot be bigger than the latest epoch"); require(validators[epoch][category][id] == address(0x0), "existing proofs cannot be modified"); validators[epoch][category][id] = _validatorAddress; emit SetProof(epoch, category, id, _validatorAddress); } /** * @dev Increments the `latestEpoch` storage variable. */ function incrementLatestEpoch() public { require(isOwner(), "only the owner can update the latest epoch"); latestEpoch = latestEpoch.add(1); emit IncrementLatestEpoch(latestEpoch); } /** * @dev Returns the common reference string. * We use a custom getter for `commonReferenceString` - the default getter created by making the storage * variable public indexes individual elements of the array, and we want to return the whole array */ function getCommonReferenceString() public view returns (bytes32[6] memory) { return commonReferenceString; } function getValidatorAddress(uint24 _proof) public view returns (address validatorAddress) { bool isValidatorDisabled; bool queryInvalid; assembly { // To compute the storage key for validatorAddress[epoch][category][id], we do the following: // 1. get the validatorAddress slot // 2. add (epoch * 0x10000) to the slot // 3. add (category * 0x100) to the slot // 4. add (id) to the slot // i.e. the range of storage pointers allocated to validatorAddress ranges from // validatorAddress_slot to (0xffff * 0x10000 + 0xff * 0x100 + 0xff = validatorAddress_slot 0xffffffff) // Conveniently, the multiplications we have to perform on epoch, category and id correspond // to their byte positions in _proof. // i.e. (epoch * 0x10000) = and(_proof, 0xffff0000) // and (category * 0x100) = and(_proof, 0xff00) // and (id) = and(_proof, 0xff) // Putting this all together. The storage slot offset from '_proof' is... // (_proof & 0xffff0000) + (_proof & 0xff00) + (_proof & 0xff) // i.e. the storage slot offset IS the value of _proof validatorAddress := sload(add(_proof, validators_slot)) queryInvalid := or(iszero(validatorAddress), isValidatorDisabled) } // wrap both require checks in a single if test. This means the happy path only has 1 conditional jump if (queryInvalid) { require(validatorAddress != address(0x0), "expected the validator address to exist"); require(isValidatorDisabled == false, "expected the validator address to not be disabled"); } } } /** * @title ZkAsset Interface * @author AZTEC * @dev An interface defining the ZkAsset standard * Copyright Spilsbury Holdings Ltd 2019. All rights reserved. **/ contract IZkAsset { event CreateZkAsset( address indexed aceAddress, address indexed linkedTokenAddress, uint256 scalingFactor, bool indexed _canAdjustSupply, bool _canConvert ); event CreateNoteRegistry(uint256 noteRegistryId); event CreateNote(address indexed owner, bytes32 indexed noteHash, bytes metadata); event DestroyNote(address indexed owner, bytes32 indexed noteHash, bytes metadata); event ConvertTokens(address indexed owner, uint256 value); event RedeemTokens(address indexed owner, uint256 value); event UpdateNoteMetadata(address indexed owner, bytes32 indexed noteHash, bytes metadata); function confidentialApprove( bytes32 _noteHash, address _spender, bool _status, bytes calldata _signature ) external; function confidentialTransferFrom(uint24 _proof, bytes calldata _proofOutput) external; function confidentialTransfer(bytes memory _proofData, bytes memory _signatures) public; } /** * @title Library of EIP712 utility constants and functions * @author AZTEC * Copyright Spilsbury Holdings Ltd 2019. All rights reserved. **/ contract LibEIP712 { // EIP712 Domain Name value string constant internal EIP712_DOMAIN_NAME = "AZTEC_CRYPTOGRAPHY_ENGINE"; // EIP712 Domain Version value string constant internal EIP712_DOMAIN_VERSION = "1"; // Hash of the EIP712 Domain Separator Schema bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); // Hash of the EIP712 Domain Separator data // solhint-disable-next-line var-name-mixedcase bytes32 public EIP712_DOMAIN_HASH; constructor () public { EIP712_DOMAIN_HASH = keccak256(abi.encode( EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(EIP712_DOMAIN_NAME)), keccak256(bytes(EIP712_DOMAIN_VERSION)), address(this) )); } /// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain. /// @param _hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to this EIP712 Domain. function hashEIP712Message(bytes32 _hashStruct) internal view returns (bytes32 _result) { bytes32 eip712DomainHash = EIP712_DOMAIN_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer. We're not going to use it - we're going to overwrite it! // We need 0x60 bytes of memory for this hash, // cheaper to overwrite the free memory pointer at 0x40, and then replace it, than allocating free memory let memPtr := mload(0x40) mstore(0x00, 0x1901) // EIP191 header mstore(0x20, eip712DomainHash) // EIP712 domain hash mstore(0x40, _hashStruct) // Hash of struct _result := keccak256(0x1e, 0x42) // compute hash // replace memory pointer mstore(0x40, memPtr) } } /// @dev Extracts the address of the signer with ECDSA. /// @param _message The EIP712 message. /// @param _signature The ECDSA values, v, r and s. /// @return The address of the message signer. function recoverSignature( bytes32 _message, bytes memory _signature ) internal view returns (address _signer) { bool result; assembly { // Here's a little trick we can pull. We expect `_signature` to be a byte array, of length 0x60, with // 'v', 'r' and 's' located linearly in memory. Preceeding this is the length parameter of `_signature`. // We *replace* the length param with the signature msg to get a memory block formatted for the precompile // load length as a temporary variable let byteLength := mload(_signature) // store the signature message mstore(_signature, _message) // load 'v' - we need it for a condition check let v := mload(add(_signature, 0x20)) result := and( and( // validate signature length == 0x60 bytes eq(byteLength, 0x60), // validate v == 27 or v == 28 or(eq(v, 27), eq(v, 28)) ), // validate call to precompile succeeds staticcall(gas, 0x01, _signature, 0x80, _signature, 0x20) ) // save the _signer only if the first word in _signature is not `_message` anymore switch eq(_message, mload(_signature)) case 0 { _signer := mload(_signature) } mstore(_signature, byteLength) // and put the byte length back where it belongs } // wrap Failure States in a single if test, so that happy path only has 1 conditional jump if (!(result && (_signer == address(0x0)))) { require(_signer != address(0x0), "signer address cannot be 0"); require(result, "signature recovery failed"); } } } /** * @title ZkAssetBase * @author AZTEC * @dev A contract defining the standard interface and behaviours of a confidential asset. * The ownership values and transfer values are encrypted. * Copyright Spilbury Holdings Ltd 2019. All rights reserved. **/ contract ZkAssetBase is IZkAsset, IAZTEC, LibEIP712 { using NoteUtils for bytes; using SafeMath for uint256; /** * Note struct. This is the data that we store when we log AZTEC notes inside a NoteRegistry * * Data structured so that the entire struct fits in 1 storage word. * * @notice Yul is used to pack and unpack Note structs in storage for efficiency reasons, * see `NoteRegistry.updateInputNotes` and `NoteRegistry.updateOutputNotes` for more details **/ struct Note { // `status` uses the IAZTEC.NoteStatus enum to track the lifecycle of a note. uint8 status; // `createdOn` logs the timestamp of the block that created this note. There are a few // use cases that require measuring the age of a note, (e.g. interest rate computations). // These lifetime are relevant on timescales of days/months, the 900-ish seconds that a miner // can manipulate a timestamp has little effect, but should be considered when utilizing this parameter. // We store `createdOn` in 5 bytes of data - just in case this contract is still around in 2038 :) // This kicks the 'year 2038' problem down the road by about 400 years uint40 createdOn; // `destroyedOn` logs the timestamp of the block that destroys this note in a transaction. // Default value is 0x0000000000 for notes that have not been spent. uint40 destroyedOn; // The owner of the note address owner; } // EIP712 Domain Name value string constant internal EIP712_DOMAIN_NAME = "ZK_ASSET"; // EIP712 Domain Version value string constant internal EIP712_DOMAIN_VERSION = "1"; bytes32 constant internal NOTE_SIGNATURE_TYPEHASH = keccak256(abi.encodePacked( "NoteSignature(", "bytes32 noteHash,", "address spender,", "bool status", ")" )); bytes32 constant internal JOIN_SPLIT_SIGNATURE_TYPE_HASH = keccak256(abi.encodePacked( "JoinSplitSignature(", "uint24 proof,", "bytes32 noteHash,", "uint256 challenge,", "address sender", ")" )); ACE public ace; IERC20 public linkedToken; uint256 public scalingFactor; mapping(bytes32 => mapping(address => bool)) public confidentialApproved; constructor( address _aceAddress, address _linkedTokenAddress, uint256 _scalingFactor, bool _canAdjustSupply ) public { bool canConvert = (_linkedTokenAddress == address(0x0)) ? false : true; EIP712_DOMAIN_HASH = keccak256(abi.encodePacked( EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(EIP712_DOMAIN_NAME)), keccak256(bytes(EIP712_DOMAIN_VERSION)), bytes32(uint256(address(this))) )); ace = ACE(_aceAddress); linkedToken = IERC20(_linkedTokenAddress); scalingFactor = _scalingFactor; ace.createNoteRegistry( _linkedTokenAddress, _scalingFactor, _canAdjustSupply, canConvert ); emit CreateZkAsset( _aceAddress, _linkedTokenAddress, _scalingFactor, _canAdjustSupply, canConvert ); } /** * @dev Executes a basic unilateral, confidential transfer of AZTEC notes * Will submit _proofData to the validateProof() function of the Cryptography Engine. * * Upon successfull verification, it will update note registry state - creating output notes and * destroying input notes. * * @param _proofData - bytes variable outputted from a proof verification contract, representing * transfer instructions for the ACE * @param _signatures - array of the ECDSA signatures over all inputNotes */ function confidentialTransfer(bytes memory _proofData, bytes memory _signatures) public { bytes memory proofOutputs = ace.validateProof(JOIN_SPLIT_PROOF, msg.sender, _proofData); confidentialTransferInternal(proofOutputs, _signatures, _proofData); } /** * @dev Note owner approving a third party, another address, to spend the note on * owner's behalf. This is necessary to allow the confidentialTransferFrom() method * to be called * * @param _noteHash - keccak256 hash of the note coordinates (gamma and sigma) * @param _spender - address being approved to spend the note * @param _status - defines whether the _spender address is being approved to spend the * note, or if permission is being revoked * @param _signature - ECDSA signature from the note owner that validates the * confidentialApprove() instruction */ function confidentialApprove( bytes32 _noteHash, address _spender, bool _status, bytes memory _signature ) public { ( uint8 status, , , ) = ace.getNote(address(this), _noteHash); require(status == 1, "only unspent notes can be approved"); bytes32 _hashStruct = keccak256(abi.encode( NOTE_SIGNATURE_TYPEHASH, _noteHash, _spender, status )); validateSignature(_hashStruct, _noteHash, _signature); confidentialApproved[_noteHash][_spender] = _status; } /** * @dev Perform ECDSA signature validation for a signature over an input note * * @param _hashStruct - the data to sign in an EIP712 signature * @param _noteHash - keccak256 hash of the note coordinates (gamma and sigma) * @param _signature - ECDSA signature for a particular input note */ function validateSignature( bytes32 _hashStruct, bytes32 _noteHash, bytes memory _signature ) internal view { (, , , address noteOwner ) = ace.getNote(address(this), _noteHash); address signer; if (_signature.length != 0) { // validate EIP712 signature bytes32 msgHash = hashEIP712Message(_hashStruct); signer = recoverSignature( msgHash, _signature ); } else { signer = msg.sender; } require(signer == noteOwner, "the note owner did not sign this message"); } /** * @dev Extract the appropriate ECDSA signature from an array of signatures, * * @param _signatures - array of ECDSA signatures over all inputNotes * @param _i - index used to determine which signature element is desired */ function extractSignature(bytes memory _signatures, uint _i) internal pure returns ( bytes memory _signature ){ bytes32 v; bytes32 r; bytes32 s; assembly { // memory map of signatures // 0x00 - 0x20 : length of signature array // 0x20 - 0x40 : first sig, v // 0x40 - 0x60 : first sig, r // 0x60 - 0x80 : first sig, s // 0x80 - 0xa0 : second sig, v // and so on... // Length of a signature = 0x60 v := mload(add(add(_signatures, 0x20), mul(_i, 0x60))) r := mload(add(add(_signatures, 0x40), mul(_i, 0x60))) s := mload(add(add(_signatures, 0x60), mul(_i, 0x60))) } _signature = abi.encode(v, r, s); } /** * @dev Executes a value transfer mediated by smart contracts. The method is supplied with * transfer instructions represented by a bytes _proofOutput argument that was outputted * from a proof verification contract. * * @param _proof - uint24 variable which acts as a unique identifier for the proof which * _proofOutput is being submitted. _proof contains three concatenated uint8 variables: * 1) epoch number 2) category number 3) ID number for the proof * @param _proofOutput - output of a zero-knowledge proof validation contract. Represents * transfer instructions for the ACE */ function confidentialTransferFrom(uint24 _proof, bytes memory _proofOutput) public { (bytes memory inputNotes, bytes memory outputNotes, address publicOwner, int256 publicValue) = _proofOutput.extractProofOutput(); uint256 length = inputNotes.getLength(); for (uint i = 0; i < length; i += 1) { (, bytes32 noteHash, ) = inputNotes.get(i).extractNote(); require( confidentialApproved[noteHash][msg.sender] == true, "sender does not have approval to spend input note" ); } ace.updateNoteRegistry(_proof, _proofOutput, msg.sender); logInputNotes(inputNotes); logOutputNotes(outputNotes); if (publicValue < 0) { emit ConvertTokens(publicOwner, uint256(-publicValue)); } if (publicValue > 0) { emit RedeemTokens(publicOwner, uint256(publicValue)); } } /** * @dev Internal method to act on transfer instructions from a successful proof validation. * Specifically, it: * - extracts the relevant objects from the proofOutput object * - validates an EIP712 signature over each input note * - updates note registry state * - emits events for note creation/destruction * - converts or redeems tokens, according to the publicValue * * @param proofOutputs - transfer instructions from a zero-knowledege proof validator * contract * @param _signatures - ECDSA signatures over a set of input notes * @param _proofData - cryptographic proof data outputted from a proof construction * operation */ function confidentialTransferInternal( bytes memory proofOutputs, bytes memory _signatures, bytes memory _proofData ) internal { bytes32 _challenge; assembly { _challenge := mload(add(_proofData, 0x40)) } for (uint i = 0; i < proofOutputs.getLength(); i += 1) { bytes memory proofOutput = proofOutputs.get(i); ace.updateNoteRegistry(JOIN_SPLIT_PROOF, proofOutput, address(this)); (bytes memory inputNotes, bytes memory outputNotes, address publicOwner, int256 publicValue) = proofOutput.extractProofOutput(); if (inputNotes.getLength() > uint(0)) { for (uint j = 0; j < inputNotes.getLength(); j += 1) { bytes memory _signature = extractSignature(_signatures, j); (, bytes32 noteHash, ) = inputNotes.get(j).extractNote(); bytes32 hashStruct = keccak256(abi.encode( JOIN_SPLIT_SIGNATURE_TYPE_HASH, JOIN_SPLIT_PROOF, noteHash, _challenge, msg.sender )); validateSignature(hashStruct, noteHash, _signature); } } logInputNotes(inputNotes); logOutputNotes(outputNotes); if (publicValue < 0) { emit ConvertTokens(publicOwner, uint256(-publicValue)); } if (publicValue > 0) { emit RedeemTokens(publicOwner, uint256(publicValue)); } } } /** * @dev Update the metadata of a note that already exists in storage. * @param noteHash - hash of a note, used as a unique identifier for the note * @param metadata - metadata to update the note with. This should be the length of * an IES encrypted viewing key, 0x177 */ function updateNoteMetaData(bytes32 noteHash, bytes calldata metadata) external { // Get the note from this assets registry ( uint8 status, , , address noteOwner ) = ace.getNote(address(this), noteHash); require(status == 1, "only unspent notes can be approved"); // There should be a permission lock here requiring that only the noteOwner can call // this function. It has been deliberately removed on a short term basis emit UpdateNoteMetadata(noteOwner, noteHash, metadata); } /** * @dev Emit events for all input notes, which represent notes being destroyed * and removed from the note registry * * @param inputNotes - input notes being destroyed and removed from note registry state */ function logInputNotes(bytes memory inputNotes) internal { for (uint i = 0; i < inputNotes.getLength(); i += 1) { (address noteOwner, bytes32 noteHash, bytes memory metadata) = inputNotes.get(i).extractNote(); emit DestroyNote(noteOwner, noteHash, metadata); } } /** * @dev Emit events for all output notes, which represent notes being created and added * to the note registry * * @param outputNotes - outputNotes being created and added to note registry state */ function logOutputNotes(bytes memory outputNotes) internal { for (uint i = 0; i < outputNotes.getLength(); i += 1) { (address noteOwner, bytes32 noteHash, bytes memory metadata) = outputNotes.get(i).extractNote(); emit CreateNote(noteOwner, noteHash, metadata); } } } /** * @title ZkAsset * @author AZTEC * @dev A contract defining the standard interface and behaviours of a confidential asset. * The ownership values and transfer values are encrypted. * Copyright Spilsbury Holdings Ltd 2019. All rights reserved. **/ contract ZkAsset is ZkAssetBase { constructor( address _aceAddress, address _linkedTokenAddress, uint256 _scalingFactor ) public ZkAssetBase( _aceAddress, _linkedTokenAddress, _scalingFactor, false // Can adjust supply ) { } } /** * @title ERC20Mintable * @dev ERC20 minting logic * Sourced from OpenZeppelin and thoroughly butchered to remove security guards. * Anybody can mint - STRICTLY FOR TEST PURPOSES */ contract ERC20Mintable is ERC20 { /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _value) public returns (bool) { _mint(_to, _value); return true; } } /** * @title ZkAssetOwnableBase * @author AZTEC * @dev A contract which inherits from ZkAsset and includes the definition * of the contract owner * Copyright Spilbury Holdings Ltd 2019. All rights reserved. **/ contract ZkAssetOwnableBase is ZkAssetBase, Ownable { using ProofUtils for uint24; using SafeMath8 for uint8; mapping(uint8 => uint256) public proofs; constructor( address _aceAddress, address _linkedTokenAddress, uint256 _scalingFactor, bool _canAdjustSupply ) public ZkAssetBase( _aceAddress, _linkedTokenAddress, _scalingFactor, _canAdjustSupply ) { } function setProofs( uint8 _epoch, uint256 _proofs ) external onlyOwner { proofs[_epoch] = _proofs; } function confidentialTransferFrom(uint24 _proof, bytes memory _proofOutput) public { bool result = supportsProof(_proof); require(result == true, "expected proof to be supported"); super.confidentialTransferFrom(_proof, _proofOutput); } // @dev Return whether the proof is supported or not by this asset. Note that we have // to subtract 1 from the proof id because the original representation is uint8, // but here that id is considered to be an exponent function supportsProof(uint24 _proof) public view returns (bool) { (uint8 epoch, uint8 category, uint8 id) = _proof.getProofComponents(); require(category == uint8(ProofCategory.BALANCED), "this asset only supports balanced proofs"); uint8 bit = uint8(proofs[epoch] >> (id.sub(1)) & 1); return bit == 1; } } /** * @title ZkAssetMintable * @author AZTEC * @dev A contract defining the standard interface and behaviours of a mintable confidential asset. * The ownership values and transfer values are encrypted. * Copyright Spilsbury Holdings Ltd 2019. All rights reserved. **/ contract ZkAssetMintableBase is ZkAssetOwnableBase { event UpdateTotalMinted(bytes32 noteHash, bytes noteData); /** * @dev Executes a confidential minting procedure, dependent on the provided proofData * being succesfully validated by the zero-knowledge validator * * @param _proof - uint24 variable which acts as a unique identifier for the proof which * _proofOutput is being submitted. _proof contains three concatenated uint8 variables: * 1) epoch number 2) category number 3) ID number for the proof * @param _proofData - bytes array of proof data, outputted from a proof construction */ function confidentialMint(uint24 _proof, bytes calldata _proofData) external onlyOwner { require(_proofData.length != 0, "proof invalid"); (bytes memory _proofOutputs) = ace.mint(_proof, _proofData, address(this)); (, bytes memory newTotal, ,) = _proofOutputs.get(0).extractProofOutput(); (, bytes memory mintedNotes, ,) = _proofOutputs.get(1).extractProofOutput(); (, bytes32 noteHash, bytes memory metadata) = newTotal.get(0).extractNote(); logOutputNotes(mintedNotes); emit UpdateTotalMinted(noteHash, metadata); } /** * @dev Executes a basic unilateral, confidential transfer of AZTEC notes adapted for use with * a mintable ZkAsset. * * Will submit _proofData to the validateProof() function of the Cryptography Engine. * * If public value is being transferred out of the ACE, and the minted value is greater than * ACE's token balance, then tokens will be minted from the linked ERC20 token using supplementTokens() * * Upon successfull verification, it will update note registry state - creating output notes and * destroying input notes. * * @param _proofData bytes variable outputted from proof construction * @param _signatures ECDSA signatures over all input notes involved in the confidentialTransfer() */ function confidentialTransfer(bytes memory _proofData, bytes memory _signatures) public { bytes memory proofOutputs = ace.validateProof(JOIN_SPLIT_PROOF, msg.sender, _proofData); require(proofOutputs.length != 0, "proof invalid"); bytes memory proofOutput = proofOutputs.get(0); (, , , int256 publicValue) = proofOutput.extractProofOutput(); ( , uint256 scalingFactor, uint256 totalSupply, , , , ) = ace.getRegistry(address(this)); if (publicValue > 0) { if (totalSupply < uint256(publicValue)) { uint256 supplementValue = uint256(publicValue).sub(totalSupply); ERC20Mintable(address(linkedToken)).mint(address(this), supplementValue.mul(scalingFactor)); ERC20Mintable(address(linkedToken)).approve(address(ace), supplementValue.mul(scalingFactor)); ace.supplementTokens(supplementValue); } } confidentialTransferInternal(proofOutputs, _signatures, _proofData); } /** * @dev Executes a value transfer mediated by smart contracts. The method is supplied with * transfer instructions represented by a bytes _proofOutput argument that was outputted * from a proof verification contract. Adapted for use with a mintable ZkAsset. * If public value is being transferred out of the ACE, and the minted value is greater than * ACE's token balance, then tokens will be minted from the linked ERC20 token using supplementTokens() * * @param _proof - uint24 variable which acts as a unique identifier for the proof which * _proofOutput is being submitted. _proof contains three concatenated uint8 variables: * 1) epoch number 2) category number 3) ID number for the proof * @param _proofOutput - output of a zero-knowledge proof validation contract. Represents * transfer instructions for the ACE */ function confidentialTransferFrom(uint24 _proof, bytes memory _proofOutput) public { (bytes memory inputNotes, bytes memory outputNotes, address publicOwner, int256 publicValue) = _proofOutput.extractProofOutput(); uint256 length = inputNotes.getLength(); for (uint i = 0; i < length; i += 1) { (, bytes32 noteHash, ) = inputNotes.get(i).extractNote(); require( confidentialApproved[noteHash][msg.sender] == true, "sender does not have approval to spend input note" ); } ( , uint256 scalingFactor, uint256 totalSupply, , , , ) = ace.getRegistry(address(this)); if (publicValue > 0) { if (totalSupply < uint256(publicValue)) { uint256 supplementValue = uint256(publicValue).sub(totalSupply); ERC20Mintable(address(linkedToken)).mint(address(this), supplementValue.mul(scalingFactor)); ERC20Mintable(address(linkedToken)).approve(address(ace), supplementValue.mul(scalingFactor)); ace.supplementTokens(supplementValue); } } ace.updateNoteRegistry(_proof, _proofOutput, msg.sender); logInputNotes(inputNotes); logOutputNotes(outputNotes); if (publicValue < 0) { emit ConvertTokens(publicOwner, uint256(-publicValue)); } if (publicValue > 0) { emit RedeemTokens(publicOwner, uint256(publicValue)); } } } /** * @title ZkAssetMintable * @author AZTEC * @dev A contract defining the standard interface and behaviours of a mintable confidential asset. * The ownership values and transfer values are encrypted. * Copyright Spilsbury Holdings Ltd 2019. All rights reserved. **/ contract ZkAssetMintable is ZkAssetMintableBase { constructor( address _aceAddress, address _linkedTokenAddress, uint256 _scalingFactor ) public ZkAssetOwnableBase( _aceAddress, _linkedTokenAddress, _scalingFactor, true // canAdjustSupply ) { } } // // contract TestZkAsset is ZkAsset { // } contract TestZKAssetMintable is ZkAssetMintable { }
Burn AZTEC notes _proof the AZTEC proof object _proofData the burn proof construction data _proofSender the Ethereum address of the original transaction sender. It is explicitly assumed that an asset using ACE supplies this field correctly - if they don't their asset is vulnerable to front-running Unnamed param is the AZTEC zero-knowledge proof data return two `bytes` objects. The first contains the new confidentialTotalSupply note and the second contains the notes that were created. Returned so that a zkAsset can emit the appropriate events/ Check that it's a burnable proof Dealing with notes representing totals Dealing with burned notes Although they are outputNotes, they are due to be destroyed - need removing from the note registry
function burn( uint24 _proof, bytes calldata _proofData, address _proofSender ) external returns (bytes memory) { Registry storage registry = registries[msg.sender]; require(registry.flags.active == true, "note registry does not exist for the given address"); require(registry.flags.canAdjustSupply == true, "this asset is not burnable"); (, uint8 category, ) = _proof.getProofComponents(); require(category == uint8(ProofCategory.BURN), "this is not a burn proof"); bytes memory _proofOutputs = this.validateProof(_proof, _proofSender, _proofData); , ) = _proofOutputs.get(0).extractProofOutput(); (, bytes32 oldTotalNoteHash, ) = oldTotal.get(0).extractNote(); require(oldTotalNoteHash == registry.confidentialTotalBurned, "provided total burned note does not match"); (, bytes32 newTotalNoteHash, ) = newTotal.get(0).extractNote(); registry.confidentialTotalBurned = newTotalNoteHash; (, bytes memory burnedNotes, ,) = _proofOutputs.get(1).extractProofOutput(); updateInputNotes(burnedNotes); return(_proofOutputs); }
6,481,777
./full_match/80001/0xb1B79A8A5729DbBF91CBC1dc135B588e36009B17/sources/contracts/WAYSPACE.sol
Start token ID for minting (1-100 vs 0-99)
function _startTokenId() internal pure override returns (uint256) { return 1; } address _zoraERC721TransferHelper, address payable _fundsRecipient
858,122
pragma solidity ^0.4.11; /** * @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; } } 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&#39;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; } } 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); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * 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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title BetrToken * @dev Betr ERC20 Token that can be minted. * It is meant to be used in BETer crowdsale contract. */ contract AtacToken is StandardToken { string public constant name = "Atlantic Coin"; string public constant symbol = "ATAC"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 500 * (10 ** 6) * (10 ** 18); /** * @dev Contructor that gives msg.sender all of existing tokens. */ function AtacToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } function getTotalSupply() public returns (uint256) { return totalSupply; } }
Contructor that gives msg.sender all of existing tokens./
function AtacToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; }
10,829,984
./full_match/1/0xF55Ec6E723d58CD9E84B9542e8335EBE4896f150/sources/contracts/PrimeMembership/Prime.sol
Alter membership record by setting member `_riskScore` _member The member address _riskScore The number up to 100 representing member's score Emits a {RiskScoreChanged} event./
function changeMemberRiskScore( address _member, uint256 _riskScore ) external nonZeroAddress(_member) onlyMember(_member) riskScoreInRange(_riskScore) onlyOwner { Member storage member = _members[_member]; if (member.riskScore != _riskScore) { member.riskScore = _riskScore; emit RiskScoreChanged(_member, _riskScore); } }
5,007,047
./partial_match/1/0xc27B0cBab6c033f0f3089F874A378Ad85b176d9F/sources/BICToken.sol
Allow another contract to spend some tokens in your behalf /
function approve(address _spender, uint256 _value) isRunning validAddress unlocked returns (bool success) { require(_value > 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
4,213,085
pragma solidity ^0.4.24; // File: contracts/lib/ownership/Ownable.sol contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner,address indexed newOwner); /// @dev The Ownable constructor sets the original `owner` of the contract to the sender account. constructor() public { owner = msg.sender; } /// @dev Throws if called by any contract other than latest designated caller modifier onlyOwner() { require(msg.sender == owner); _; } /// @dev Allows the current owner to transfer control of the contract to a newOwner. /// @param newOwner The address to transfer ownership to. function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/lib/ownership/ZapCoordinatorInterface.sol contract ZapCoordinatorInterface is Ownable { function addImmutableContract(string contractName, address newAddress) external; function updateContract(string contractName, address newAddress) external; function getContractName(uint index) public view returns (string); function getContract(string contractName) public view returns (address); function updateAllDependencies() external; } // File: contracts/lib/ownership/Upgradable.sol pragma solidity ^0.4.24; contract Upgradable { address coordinatorAddr; ZapCoordinatorInterface coordinator; constructor(address c) public{ coordinatorAddr = c; coordinator = ZapCoordinatorInterface(c); } function updateDependencies() external coordinatorOnly { _updateDependencies(); } function _updateDependencies() internal; modifier coordinatorOnly() { require(msg.sender == coordinatorAddr, "Error: Coordinator Only Function"); _; } } // File: contracts/lib/lifecycle/Destructible.sol contract Destructible is Ownable { function selfDestruct() public onlyOwner { selfdestruct(owner); } } // File: contracts/lib/platform/Client.sol contract Client1 { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response1 first provider-specified param function callback(uint256 id, string response1) external; } contract Client2 { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response1 first provider-specified param /// @param response2 second provider-specified param function callback(uint256 id, string response1, string response2) external; } contract Client3 { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response1 first provider-specified param /// @param response2 second provider-specified param /// @param response3 third provider-specified param function callback(uint256 id, string response1, string response2, string response3) external; } contract Client4 { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response1 first provider-specified param /// @param response2 second provider-specified param /// @param response3 third provider-specified param /// @param response4 fourth provider-specified param function callback(uint256 id, string response1, string response2, string response3, string response4) external; } contract ClientBytes32Array { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response bytes32 array function callback(uint256 id, bytes32[] response) external; } contract ClientIntArray{ /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response int array function callback(uint256 id, int[] response) external; } // File: contracts/lib/platform/OnChainProvider.sol contract OnChainProvider { /// @dev function for requesting data from on-chain provider /// @param id request id /// @param userQuery query string /// @param endpoint endpoint specifier ala 'smart_contract' /// @param endpointParams endpoint-specific params function receive(uint256 id, string userQuery, bytes32 endpoint, bytes32[] endpointParams, bool onchainSubscriber) external; } // File: contracts/platform/bondage/BondageInterface.sol contract BondageInterface { function bond(address, bytes32, uint256) external returns(uint256); function unbond(address, bytes32, uint256) external returns (uint256); function delegateBond(address, address, bytes32, uint256) external returns(uint256); function escrowDots(address, address, bytes32, uint256) external returns (bool); function releaseDots(address, address, bytes32, uint256) external returns (bool); function returnDots(address, address, bytes32, uint256) external returns (bool success); function calcZapForDots(address, bytes32, uint256) external view returns (uint256); function currentCostOfDot(address, bytes32, uint256) public view returns (uint256); function getDotsIssued(address, bytes32) public view returns (uint256); function getBoundDots(address, address, bytes32) public view returns (uint256); function getZapBound(address, bytes32) public view returns (uint256); function dotLimit( address, bytes32) public view returns (uint256); } // File: contracts/platform/dispatch/DispatchInterface.sol interface DispatchInterface { function query(address, string, bytes32, bytes32[]) external returns (uint256); function respond1(uint256, string) external returns (bool); function respond2(uint256, string, string) external returns (bool); function respond3(uint256, string, string, string) external returns (bool); function respond4(uint256, string, string, string, string) external returns (bool); function respondBytes32Array(uint256, bytes32[]) external returns (bool); function respondIntArray(uint256,int[] ) external returns (bool); function cancelQuery(uint256) external; function getProvider(uint256 id) public view returns (address); function getSubscriber(uint256 id) public view returns (address); function getEndpoint(uint256 id) public view returns (bytes32); function getStatus(uint256 id) public view returns (uint256); function getCancel(uint256 id) public view returns (uint256); function getUserQuery(uint256 id) public view returns (string); function getSubscriberOnchain(uint256 id) public view returns (bool); } // File: contracts/platform/database/DatabaseInterface.sol contract DatabaseInterface is Ownable { function setStorageContract(address _storageContract, bool _allowed) public; /*** Bytes32 ***/ function getBytes32(bytes32 key) external view returns(bytes32); function setBytes32(bytes32 key, bytes32 value) external; /*** Number **/ function getNumber(bytes32 key) external view returns(uint256); function setNumber(bytes32 key, uint256 value) external; /*** Bytes ***/ function getBytes(bytes32 key) external view returns(bytes); function setBytes(bytes32 key, bytes value) external; /*** String ***/ function getString(bytes32 key) external view returns(string); function setString(bytes32 key, string value) external; /*** Bytes Array ***/ function getBytesArray(bytes32 key) external view returns (bytes32[]); function getBytesArrayIndex(bytes32 key, uint256 index) external view returns (bytes32); function getBytesArrayLength(bytes32 key) external view returns (uint256); function pushBytesArray(bytes32 key, bytes32 value) external; function setBytesArrayIndex(bytes32 key, uint256 index, bytes32 value) external; function setBytesArray(bytes32 key, bytes32[] value) external; /*** Int Array ***/ function getIntArray(bytes32 key) external view returns (int[]); function getIntArrayIndex(bytes32 key, uint256 index) external view returns (int); function getIntArrayLength(bytes32 key) external view returns (uint256); function pushIntArray(bytes32 key, int value) external; function setIntArrayIndex(bytes32 key, uint256 index, int value) external; function setIntArray(bytes32 key, int[] value) external; /*** Address Array ***/ function getAddressArray(bytes32 key) external view returns (address[]); function getAddressArrayIndex(bytes32 key, uint256 index) external view returns (address); function getAddressArrayLength(bytes32 key) external view returns (uint256); function pushAddressArray(bytes32 key, address value) external; function setAddressArrayIndex(bytes32 key, uint256 index, address value) external; function setAddressArray(bytes32 key, address[] value) external; } // File: contracts/platform/dispatch/Dispatch.sol // v1.0 contract Dispatch is Destructible, DispatchInterface, Upgradable { enum Status { Pending, Fulfilled, Canceled } //event data provider is listening for, containing all relevant request parameters event Incoming( uint256 indexed id, address indexed provider, address indexed subscriber, string query, bytes32 endpoint, bytes32[] endpointParams, bool onchainSubscriber ); event FulfillQuery( address indexed subscriber, address indexed provider, bytes32 indexed endpoint ); event OffchainResponse( uint256 indexed id, address indexed subscriber, address indexed provider, bytes32[] response ); event OffchainResponseInt( uint256 indexed id, address indexed subscriber, address indexed provider, int[] response ); event OffchainResult1( uint256 indexed id, address indexed subscriber, address indexed provider, string response1 ); event OffchainResult2( uint256 indexed id, address indexed subscriber, address indexed provider, string response1, string response2 ); event OffchainResult3( uint256 indexed id, address indexed subscriber, address indexed provider, string response1, string response2, string response3 ); event OffchainResult4( uint256 indexed id, address indexed subscriber, address indexed provider, string response1, string response2, string response3, string response4 ); event CanceledRequest( uint256 indexed id, address indexed subscriber, address indexed provider ); event RevertCancelation( uint256 indexed id, address indexed subscriber, address indexed provider ); BondageInterface public bondage; address public bondageAddress; DatabaseInterface public db; constructor(address c) Upgradable(c) public { //_updateDependencies(); } function _updateDependencies() internal { address databaseAddress = coordinator.getContract("DATABASE"); db = DatabaseInterface(databaseAddress); bondageAddress = coordinator.getContract("BONDAGE"); bondage = BondageInterface(bondageAddress); } /// @notice Escrow dot for oracle request /// @dev Called by user contract function query( address provider, // data provider address string userQuery, // query string bytes32 endpoint, // endpoint specifier ala 'smart_contract' bytes32[] endpointParams // endpoint-specific params ) external returns (uint256 id) { uint256 dots = bondage.getBoundDots(msg.sender, provider, endpoint); bool onchainProvider = isContract(provider); bool onchainSubscriber = isContract(msg.sender); if(dots >= 1) { //enough dots bondage.escrowDots(msg.sender, provider, endpoint, 1); id = uint256(keccak256(abi.encodePacked(block.number, now, userQuery, msg.sender, provider))); createQuery(id, provider, msg.sender, endpoint, userQuery, onchainSubscriber); if(onchainProvider) { OnChainProvider(provider).receive(id, userQuery, endpoint, endpointParams, onchainSubscriber); } else{ emit Incoming(id, provider, msg.sender, userQuery, endpoint, endpointParams, onchainSubscriber); } } else { // NOT ENOUGH DOTS revert("Subscriber does not have any dots."); } } /// @notice Transfer dots from Bondage escrow to data provider's Holder object under its own address /// @dev Called upon data-provider request fulfillment function fulfillQuery(uint256 id) private returns (bool) { Status status = Status(getStatus(id)); require(status != Status.Fulfilled, "Error: Status already fulfilled"); address subscriber = getSubscriber(id); address provider = getProvider(id); bytes32 endpoint = getEndpoint(id); if ( status == Status.Canceled ) { uint256 canceled = getCancel(id); // Make sure we've canceled in the past, // if it's current block ignore the cancel require(block.number == canceled, "Error: Cancel ignored"); // Uncancel the query setCanceled(id, false); // Re-escrow the previously returned dots bondage.escrowDots(subscriber, provider, endpoint, 1); // Emit the events emit RevertCancelation(id, subscriber, provider); } setFulfilled(id); bondage.releaseDots(subscriber, provider, endpoint, 1); emit FulfillQuery(subscriber, provider, endpoint); return true; } /// @notice Cancel a query. /// @dev If responded on the same block, ignore the cancel. function cancelQuery(uint256 id) external { address subscriber = getSubscriber(id); address provider = getProvider(id); bytes32 endpoint = getEndpoint(id); require(subscriber == msg.sender, "Error: Wrong subscriber"); require(Status(getStatus(id)) == Status.Pending, "Error: Query is not pending"); // Cancel the query setCanceled(id, true); // Return the dots to the subscriber bondage.returnDots(subscriber, provider, endpoint, 1); // Release an event emit CanceledRequest(id, getSubscriber(id), getProvider(id)); } /// @dev Parameter-count specific method called by data provider in response function respondBytes32Array( uint256 id, bytes32[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientBytes32Array(getSubscriber(id)).callback(id, response); } else { emit OffchainResponse(id, getSubscriber(id), msg.sender, response); } return true; } /// @dev Parameter-count specific method called by data provider in response function respondIntArray( uint256 id, int[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientIntArray(getSubscriber(id)).callback(id, response); } else { emit OffchainResponseInt(id, getSubscriber(id), msg.sender, response); } return true; } /// @dev Parameter-count specific method called by data provider in response function respond1( uint256 id, string response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client1(getSubscriber(id)).callback(id, response); } else { emit OffchainResult1(id, getSubscriber(id), msg.sender, response); } return true; } /// @dev Parameter-count specific method called by data provider in response function respond2( uint256 id, string response1, string response2 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client2(getSubscriber(id)).callback(id, response1, response2); } else { emit OffchainResult2(id, getSubscriber(id), msg.sender, response1, response2); } return true; } /// @dev Parameter-count specific method called by data provider in response function respond3( uint256 id, string response1, string response2, string response3 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client3(getSubscriber(id)).callback(id, response1, response2, response3); } else { emit OffchainResult3(id, getSubscriber(id), msg.sender, response1, response2, response3); } return true; } /// @dev Parameter-count specific method called by data provider in response function respond4( uint256 id, string response1, string response2, string response3, string response4 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client4(getSubscriber(id)).callback(id, response1, response2, response3, response4); } else { emit OffchainResult4(id, getSubscriber(id), msg.sender, response1, response2, response3, response4); } return true; } /*** STORAGE METHODS ***/ /// @dev get provider address of request /// @param id request id function getProvider(uint256 id) public view returns (address) { return address(db.getNumber(keccak256(abi.encodePacked('queries', id, 'provider')))); } /// @dev get subscriber address of request /// @param id request id function getSubscriber(uint256 id) public view returns (address) { return address(db.getNumber(keccak256(abi.encodePacked('queries', id, 'subscriber')))); } /// @dev get endpoint of request /// @param id request id function getEndpoint(uint256 id) public view returns (bytes32) { return db.getBytes32(keccak256(abi.encodePacked('queries', id, 'endpoint'))); } /// @dev get status of request /// @param id request id function getStatus(uint256 id) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('queries', id, 'status'))); } /// @dev get the cancelation block of a request /// @param id request id function getCancel(uint256 id) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock'))); } /// @dev get user specified query of request /// @param id request id function getUserQuery(uint256 id) public view returns (string) { return db.getString(keccak256(abi.encodePacked('queries', id, 'userQuery'))); } /// @dev is subscriber contract or offchain /// @param id request id function getSubscriberOnchain(uint256 id) public view returns (bool) { uint res = db.getNumber(keccak256(abi.encodePacked('queries', id, 'onchainSubscriber'))); return res == 1 ? true : false; } /**** Set Methods ****/ function createQuery( uint256 id, address provider, address subscriber, bytes32 endpoint, string userQuery, bool onchainSubscriber ) private { db.setNumber(keccak256(abi.encodePacked('queries', id, 'provider')), uint256(provider)); db.setNumber(keccak256(abi.encodePacked('queries', id, 'subscriber')), uint256(subscriber)); db.setBytes32(keccak256(abi.encodePacked('queries', id, 'endpoint')), endpoint); db.setString(keccak256(abi.encodePacked('queries', id, 'userQuery')), userQuery); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending)); db.setNumber(keccak256(abi.encodePacked('queries', id, 'onchainSubscriber')), onchainSubscriber ? 1 : 0); } function setFulfilled(uint256 id) private { db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Fulfilled)); } function setCanceled(uint256 id, bool canceled) private { if ( canceled ) { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), block.number); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Canceled)); } else { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), 0); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending)); } } function isContract(address addr) private view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } /* /* For use in example contract, see TestContracts.sol /* /* When User Contract calls ZapDispatch.query(), /* 1 oracle specific dot is escrowed by ZapBondage and Incoming event is ted. /* /* When provider's client hears an Incoming event containing provider's address and responds, /* the provider calls a ZapDispatch.respondX function corresponding to number of response params. /* /* Dots are moved from ZapBondage escrow to data-provider's bond Holder struct, /* with data provider address set as self's address. /*/ /*************************************** STORAGE **************************************** * 'queries', id, 'provider' => {address} address of provider that this query was sent to * 'queries', id, 'subscriber' => {address} address of subscriber that this query was sent by * 'queries', id, 'endpoint' => {bytes32} endpoint that this query was sent to * 'queries', id, 'status' => {Status} current status of this query * 'queries', id, 'cancelBlock' => {uint256} the block number of the cancellation request (0 if none) * 'queries', id, 'userQuery' => {uint256} the query that was sent with this queryId * 'queries', id, 'onchainSubscriber' => {uint256} 1 -> onchainSubscriber, 0 -> offchainSubscriber ****************************************************************************************/
Parameter-count specific method called by data provider in response
function respond4( uint256 id, string response1, string response2, string response3, string response4 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client4(getSubscriber(id)).callback(id, response1, response2, response3, response4); } else { emit OffchainResult4(id, getSubscriber(id), msg.sender, response1, response2, response3, response4); } return true; }
7,219,464
./partial_match/1/0x2870C0E17257934bd77B8a903d35e57a5Bccc174/sources/NAT3.sol
widraw ETH from this contract.only operator. /
function withdraw() external payable virtual onlyOperator nonReentrant{ uint256 _ethBalance = address(this).balance; bool os; } require(os, "Failed to withdraw Ether");
16,111,439
./partial_match/42/0xaa4b8A9720c5C02aFA23e29dA6121BD7Dba4d0F6/sources/JCompound.sol
get Tranche A exchange rate _trancheNum tranche number return tranche A token current price/trancheParameters[_trancheNum].lastABlockAction = block.number;
function calcRPBFromPercentage(uint256 _trancheNum) public returns (uint256) { trancheParameters[_trancheNum].trancheACurrentRPB = trancheParameters[_trancheNum].storedTrancheAPrice .mul(trancheParameters[_trancheNum].trancheAFixedPercentage).div(totalBlockPerYears).div(1e18); return trancheParameters[_trancheNum].trancheACurrentRPB; }
3,475,585
./full_match/8453/0x8F422B7f6e7cE2B25CC847255DE724a22D26dc86/sources/contracts/Facets/DiamondLoupeFacet.sol
Gets all the function selectors provided by a facet. _facet The facet address. return facetFunctionSelectors_
function facetFunctionSelectors( address _facet ) external view override returns (bytes4[] memory facetFunctionSelectors_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); facetFunctionSelectors_ = ds.facetFunctionSelectors[_facet].functionSelectors; }
11,547,201
./full_match/5/0x76134eE647D72c371E489e35404CC7B5C76B612c/sources/contracts/libraries/eigenda/lib/contracts/libraries/BLS.sol
(N + 1) / 4 = 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52 N = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
function sqrt(uint256 xx) internal view returns (uint256 x, bool hasRoot) { bool callSuccess; assembly { let freemem := mload(0x40) mstore(freemem, 0x20) mstore(add(freemem, 0x20), 0x20) mstore(add(freemem, 0x40), 0x20) mstore(add(freemem, 0x60), xx) mstore(add(freemem, 0x80), 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52) mstore(add(freemem, 0xA0), 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47) callSuccess := staticcall(sub(gas(), 2000), 5, freemem, 0xC0, freemem, 0x20) x := mload(freemem) hasRoot := eq(xx, mulmod(x, x, MODULUS)) } require(callSuccess, "BLS: sqrt modexp call failed"); }
7,036,643
pragma solidity ^0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface token { function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function allowance(address, address) external constant returns (uint256); function balanceOf(address) external constant returns (uint256); } /** LOGIC DESCRIPTION * 11% fees in and out for ETH * 11% fees in and out for NOVA * * ETH fees split: * 6% to nova holders * 4% to eth holders * 1% to fixed address * * NOVA fees split: * 6% to nova holders * 4% to eth holders * 1% airdrop to a random address based on their nova shares * rules: * - you need to have both nova and eth to get dividends */ contract NovaBox is Ownable { using SafeMath for uint; token tokenReward; constructor() public { tokenReward = token(0x72FBc0fc1446f5AcCC1B083F0852a7ef70a8ec9f); } event AirDrop(address to, uint amount, uint randomTicket); event DividendsTransferred(address to, uint ethAmount, uint novaAmount); // ether contributions mapping (address => uint) public contributionsEth; // token contributions mapping (address => uint) public contributionsToken; // investors list who have deposited BOTH ether and token mapping (address => uint) public indexes; mapping (uint => address) public addresses; uint256 public lastIndex = 0; mapping (address => bool) public addedToList; uint _totalTokens = 0; uint _totalWei = 0; uint pointMultiplier = 1e18; mapping (address => uint) public last6EthDivPoints; uint public total6EthDivPoints = 0; // uint public unclaimed6EthDivPoints = 0; mapping (address => uint) public last4EthDivPoints; uint public total4EthDivPoints = 0; // uint public unclaimed4EthDivPoints = 0; mapping (address => uint) public last6TokenDivPoints; uint public total6TokenDivPoints = 0; // uint public unclaimed6TokenDivPoints = 0; mapping (address => uint) public last4TokenDivPoints; uint public total4TokenDivPoints = 0; // uint public unclaimed4TokenDivPoints = 0; function ethDivsOwing(address _addr) public view returns (uint) { return eth4DivsOwing(_addr).add(eth6DivsOwing(_addr)); } function eth6DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newEth6DivPoints = total6EthDivPoints.sub(last6EthDivPoints[_addr]); return contributionsToken[_addr].mul(newEth6DivPoints).div(pointMultiplier); } function eth4DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newEth4DivPoints = total4EthDivPoints.sub(last4EthDivPoints[_addr]); return contributionsEth[_addr].mul(newEth4DivPoints).div(pointMultiplier); } function tokenDivsOwing(address _addr) public view returns (uint) { return token4DivsOwing(_addr).add(token6DivsOwing(_addr)); } function token6DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newToken6DivPoints = total6TokenDivPoints.sub(last6TokenDivPoints[_addr]); return contributionsToken[_addr].mul(newToken6DivPoints).div(pointMultiplier); } function token4DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newToken4DivPoints = total4TokenDivPoints.sub(last4TokenDivPoints[_addr]); return contributionsEth[_addr].mul(newToken4DivPoints).div(pointMultiplier); } function updateAccount(address account) private { uint owingEth6 = eth6DivsOwing(account); uint owingEth4 = eth4DivsOwing(account); uint owingEth = owingEth4.add(owingEth6); uint owingToken6 = token6DivsOwing(account); uint owingToken4 = token4DivsOwing(account); uint owingToken = owingToken4.add(owingToken6); if (owingEth > 0) { // send ether dividends to account account.transfer(owingEth); } if (owingToken > 0) { // send token dividends to account tokenReward.transfer(account, owingToken); } last6EthDivPoints[account] = total6EthDivPoints; last4EthDivPoints[account] = total4EthDivPoints; last6TokenDivPoints[account] = total6TokenDivPoints; last4TokenDivPoints[account] = total4TokenDivPoints; emit DividendsTransferred(account, owingEth, owingToken); } function addToList(address sender) private { addedToList[sender] = true; // if the sender is not in the list if (indexes[sender] == 0) { _totalTokens = _totalTokens.add(contributionsToken[sender]); _totalWei = _totalWei.add(contributionsEth[sender]); // add the sender to the list lastIndex++; addresses[lastIndex] = sender; indexes[sender] = lastIndex; } } function removeFromList(address sender) private { addedToList[sender] = false; // if the sender is in temp eth list if (indexes[sender] > 0) { _totalTokens = _totalTokens.sub(contributionsToken[sender]); _totalWei = _totalWei.sub(contributionsEth[sender]); // remove the sender from temp eth list addresses[indexes[sender]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[sender]; indexes[sender] = 0; delete addresses[lastIndex]; lastIndex--; } } // desposit ether function () payable public { address sender = msg.sender; // size of code at target address uint codeLength; // get the length of code at the sender address assembly { codeLength := extcodesize(sender) } // don't allow contracts to deposit ether require(codeLength == 0); uint weiAmount = msg.value; updateAccount(sender); // number of ether sent must be greater than 0 require(weiAmount > 0); uint _89percent = weiAmount.mul(89).div(100); uint _6percent = weiAmount.mul(6).div(100); uint _4percent = weiAmount.mul(4).div(100); uint _1percent = weiAmount.mul(1).div(100); distributeEth( _6percent, // to nova investors _4percent // to eth investors ); //1% goes to REX Investors owner.transfer(_1percent); contributionsEth[sender] = contributionsEth[sender].add(_89percent); // if the sender is in list if (indexes[sender]>0) { // increase _totalWei _totalWei = _totalWei.add(_89percent); } // if the sender has also deposited tokens, add sender to list if (contributionsToken[sender]>0) addToList(sender); } // withdraw ether function withdrawEth(uint amount) public { address sender = msg.sender; require(amount>0 && contributionsEth[sender] >= amount); updateAccount(sender); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); contributionsEth[sender] = contributionsEth[sender].sub(amount); // if sender is in list if (indexes[sender]>0) { // decrease total wei _totalWei = _totalWei.sub(amount); } // if the sender has withdrawn all their eth // remove the sender from list if (contributionsEth[sender] == 0) removeFromList(sender); sender.transfer(_89percent); distributeEth( _6percent, // to nova investors _4percent // to eth investors ); owner.transfer(_1percent); //1% goes to REX Investors } // deposit tokens function depositTokens(address randomAddr, uint randomTicket) public { updateAccount(msg.sender); address sender = msg.sender; uint amount = tokenReward.allowance(sender, address(this)); // number of allowed tokens must be greater than 0 // if it is then transfer the allowed tokens from sender to the contract // if not transferred then throw require(amount>0 && tokenReward.transferFrom(sender, address(this), amount)); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); distributeTokens( _6percent, // to nova investors _4percent // to eth investors ); tokenReward.transfer(randomAddr, _1percent); // 1% for Airdrop emit AirDrop(randomAddr, _1percent, randomTicket); contributionsToken[sender] = contributionsToken[sender].add(_89percent); // if sender is in list if (indexes[sender]>0) { // increase totaltokens _totalTokens = _totalTokens.add(_89percent); } // if the sender has also contributed ether add sender to list if (contributionsEth[sender]>0) addToList(sender); } // withdraw tokens function withdrawTokens(uint amount, address randomAddr, uint randomTicket) public { address sender = msg.sender; updateAccount(sender); // requested amount must be greater than 0 and // the sender must have contributed tokens no less than `amount` require(amount>0 && contributionsToken[sender]>=amount); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); contributionsToken[sender] = contributionsToken[sender].sub(amount); // if sender is in list if (indexes[sender]>0) { // decrease total tokens _totalTokens = _totalTokens.sub(amount); } // if sender withdrawn all their tokens, remove them from list if (contributionsToken[sender] == 0) removeFromList(sender); tokenReward.transfer(sender, _89percent); distributeTokens( _6percent, // to nova investors _4percent // to eth investors ); // airdropToRandom(_1percent); tokenReward.transfer(randomAddr, _1percent); emit AirDrop(randomAddr, _1percent, randomTicket); } function distributeTokens(uint _6percent, uint _4percent) private { uint totalTokens = getTotalTokens(); uint totalWei = getTotalWei(); if (totalWei == 0 || totalTokens == 0) return; total4TokenDivPoints = total4TokenDivPoints.add(_4percent.mul(pointMultiplier).div(totalWei)); // unclaimed4TokenDivPoints = unclaimed4TokenDivPoints.add(_4percent); total6TokenDivPoints = total6TokenDivPoints.add(_6percent.mul(pointMultiplier).div(totalTokens)); // unclaimed6TokenDivPoints = unclaimed6TokenDivPoints.add(_6percent); } function distributeEth(uint _6percent, uint _4percent) private { uint totalTokens = getTotalTokens(); uint totalWei = getTotalWei(); if (totalWei ==0 || totalTokens == 0) return; total4EthDivPoints = total4EthDivPoints.add(_4percent.mul(pointMultiplier).div(totalWei)); // unclaimed4EthDivPoints += _4percent; total6EthDivPoints = total6EthDivPoints.add(_6percent.mul(pointMultiplier).div(totalTokens)); // unclaimed6EthDivPoints += _6percent; } // get sum of tokens contributed by the ether investors function getTotalTokens() public view returns (uint) { return _totalTokens; } // get the sum of wei contributed by the token investors function getTotalWei() public view returns (uint) { return _totalWei; } function withdrawDivs() public { updateAccount(msg.sender); } // get the list of investors function getList() public view returns (address[], uint[]) { address[] memory _addrs = new address[](lastIndex); uint[] memory _contributions = new uint[](lastIndex); for (uint i = 1; i <= lastIndex; i++) { _addrs[i-1] = addresses[i]; _contributions[i-1] = contributionsToken[addresses[i]]; } return (_addrs, _contributions); } }
withdraw tokens requested amount must be greater than 0 and the sender must have contributed tokens no less than `amount` if sender is in list decrease total tokens
function withdrawTokens(uint amount, address randomAddr, uint randomTicket) public { address sender = msg.sender; updateAccount(sender); require(amount>0 && contributionsToken[sender]>=amount); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); contributionsToken[sender] = contributionsToken[sender].sub(amount); if (indexes[sender]>0) { _totalTokens = _totalTokens.sub(amount); } tokenReward.transfer(sender, _89percent); distributeTokens( ); emit AirDrop(randomAddr, _1percent, randomTicket); }
2,501,411
/** @title Onasander Token Contract * * @author: Andrzej Wegrzyn * Contact: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6828390838a89968b838892a6898887958788828394c885898b">[email&#160;protected]</a> * Date: May 5, 2018 * Location: New York, USA * Token: Onasander * Symbol: ONA * * @notice This is a simple contract due to solidity bugs and complications. * * @notice Owner has the option to burn all the remaining tokens after the ICO. That way Owners will not end up with majority of the tokens. * @notice Onasander would love to give every user the option to burn the remaining tokens, but due to Solidity VM bugs and risk, we will process * @notice all coin burns and refunds manually. * * @notice How to run the contract: * * Requires: * Wallet Address * * Run: * 1. Create Contract * 2. Set Minimum Goal * 3. Set Tokens Per ETH * 4. Create PRE ICO Sale (can have multiple PRE-ICOs) * 5. End PRE ICO Sale * 6. Create ICO Sale * 7. End ICO Sale * 8. END ICO * 9. Burn Remaining Tokens * * e18 for every value except tokens per ETH * * @dev This contract allows you to configure as many Pre-ICOs as you need. It&#39;s a very simple contract written to give contract admin lots of dynamic options. * @dev Here, most features except for total supply, max tokens for sale, company reserves, and token standard features, are dynamic. You can configure your contract * @dev however you want to. * * @dev IDE: Remix with Mist 0.10 * @dev Token supply numbers are provided in 0e18 format in MIST in order to bypass MIST number format errors. */ pragma solidity ^0.4.23; contract OnasanderToken { using SafeMath for uint; address private wallet; // Address where funds are collected address public owner; // contract owner string constant public name = "Onasander"; string constant public symbol = "ONA"; uint8 constant public decimals = 18; uint public totalSupply = 88000000e18; uint public totalTokensSold = 0e18; // total number of tokens sold to date uint public totalTokensSoldInThisSale = 0e18; // total number of tokens sold in this sale uint public maxTokensForSale = 79200000e18; // 90% max tokens we can ever sale uint public companyReserves = 8800000e18; // 10% company reserves. this is what we end up with after eco ends and burns the rest if any uint public minimumGoal = 0e18; // hold minimum goal uint public tokensForSale = 0e18; // total number of tokens we are selling in the current sale (ICO, preICO) bool public saleEnabled = false; // enables all sales: ICO and tokensPreICO bool public ICOEnded = false; // flag checking if the ICO has completed bool public burned = false; // Excess tokens burned flag after ICO ends uint public tokensPerETH = 800; // amount of Onasander tokens you get for 1 ETH bool public wasGoalReached = false; // checks if minimum goal was reached address private lastBuyer; uint private singleToken = 1e18; constructor(address icoWallet) public { require(icoWallet != address(0), "ICO Wallet address is required."); owner = msg.sender; wallet = icoWallet; balances[owner] = totalSupply; // give initial full balance to contract owner emit TokensMinted(owner, totalSupply); } event ICOHasEnded(); event SaleEnded(); event OneTokenBugFixed(); event ICOConfigured(uint minimumGoal); event TokenPerETHReset(uint amount); event ICOCapReached(uint amount); event SaleCapReached(uint amount); event GoalReached(uint amount); event Burned(uint amount); event BuyTokens(address buyer, uint tokens); event SaleStarted(uint tokensForSale); event TokensMinted(address targetAddress, uint tokens); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); mapping(address => uint) balances; mapping(address => mapping (address => uint)) allowances; function balanceOf(address accountAddress) public constant returns (uint balance) { return balances[accountAddress]; } function allowance(address sender, address spender) public constant returns (uint remainingAllowedAmount) { return allowances[sender][spender]; } function transfer(address to, uint tokens) public returns (bool success) { require (ICOEnded, "ICO has not ended. Can not transfer."); require (balances[to] + tokens > balances[to], "Overflow is not allowed."); // actual transfer // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns(bool success) { require (ICOEnded, "ICO has not ended. Can not transfer."); require (balances[to] + tokens > balances[to], "Overflow is not allowed."); // actual transfer balances[from] = balances[from].sub(tokens); allowances[from][msg.sender] = allowances[from][msg.sender].sub(tokens); // lower the allowance by the amount of tokens balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function approve(address spender, uint tokens) public returns(bool success) { require (ICOEnded, "ICO has not ended. Can not transfer."); allowances[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // in case some investor pays by wire or credit card we will transfer him the tokens manually. function wirePurchase(address to, uint numberOfTokenPurchased) onlyOwner public { require (saleEnabled, "Sale must be enabled."); require (!ICOEnded, "ICO already ended."); require (numberOfTokenPurchased > 0, "Tokens must be greater than 0."); require (tokensForSale > totalTokensSoldInThisSale, "There is no more tokens for sale in this sale."); // calculate amount uint buyAmount = numberOfTokenPurchased; uint tokens = 0e18; // this check is not perfect as someone may want to buy more than we offer for sale and we lose a sale. // the best would be to calclate and sell you only the amout of tokens that is left and refund the rest of money if (totalTokensSoldInThisSale.add(buyAmount) >= tokensForSale) { tokens = tokensForSale.sub(totalTokensSoldInThisSale); // we allow you to buy only up to total tokens for sale, and refund the rest // need to program the refund for the rest,or do it manually. } else { tokens = buyAmount; } // transfer only as we do not need to take the payment since we already did in wire require (balances[to].add(tokens) > balances[to], "Overflow is not allowed."); balances[to] = balances[to].add(tokens); balances[owner] = balances[owner].sub(tokens); lastBuyer = to; // update counts totalTokensSold = totalTokensSold.add(tokens); totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(tokens); emit BuyTokens(to, tokens); emit Transfer(owner, to, tokens); isGoalReached(); isMaxCapReached(); } function buyTokens() payable public { require (saleEnabled, "Sale must be enabled."); require (!ICOEnded, "ICO already ended."); require (tokensForSale > totalTokensSoldInThisSale, "There is no more tokens for sale in this sale."); require (msg.value > 0, "Must send ETH"); // calculate amount uint buyAmount = SafeMath.mul(msg.value, tokensPerETH); uint tokens = 0e18; // this check is not perfect as someone may want to buy more than we offer for sale and we lose a sale. // the best would be to calclate and sell you only the amout of tokens that is left and refund the rest of money if (totalTokensSoldInThisSale.add(buyAmount) >= tokensForSale) { tokens = tokensForSale.sub(totalTokensSoldInThisSale); // we allow you to buy only up to total tokens for sale, and refund the rest // need to program the refund for the rest } else { tokens = buyAmount; } // buy require (balances[msg.sender].add(tokens) > balances[msg.sender], "Overflow is not allowed."); balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); lastBuyer = msg.sender; // take the money out right away wallet.transfer(msg.value); // update counts totalTokensSold = totalTokensSold.add(tokens); totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(tokens); emit BuyTokens(msg.sender, tokens); emit Transfer(owner, msg.sender, tokens); isGoalReached(); isMaxCapReached(); } // Fallback function. Used for buying tokens from contract owner by simply // sending Ethers to contract. function() public payable { // we buy tokens using whatever ETH was sent in buyTokens(); } // Called when ICO is closed. Burns the remaining tokens except the tokens reserved // Must be called by the owner to trigger correct transfer event function burnRemainingTokens() public onlyOwner { require (!burned, "Remaining tokens have been burned already."); require (ICOEnded, "ICO has not ended yet."); uint difference = balances[owner].sub(companyReserves); if (wasGoalReached) { totalSupply = totalSupply.sub(difference); balances[owner] = companyReserves; } else { // in case we did not reach the goal, we burn all tokens except tokens purchased. totalSupply = totalTokensSold; balances[owner] = 0e18; } burned = true; emit Transfer(owner, address(0), difference); // this is run in order to update token holders in the website emit Burned(difference); } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { address preOwner = owner; owner = newOwner; uint previousBalance = balances[preOwner]; // transfer balance balances[newOwner] = balances[newOwner].add(previousBalance); balances[preOwner] = 0; //emit Transfer(preOwner, newOwner, previousBalance); // required to update the Token Holders on the network emit OwnershipTransferred(preOwner, newOwner, previousBalance); } // Set the number of ONAs sold per ETH function setTokensPerETH(uint newRate) onlyOwner public { require (!ICOEnded, "ICO already ended."); require (newRate > 0, "Rate must be higher than 0."); tokensPerETH = newRate; emit TokenPerETHReset(newRate); } // Minimum goal is based on USD, not on ETH. Since we will have different dynamic prices based on the daily pirce of ETH, we // will need to be able to adjust our minimum goal in tokens sold, as our goal is set in tokens, not USD. function setMinimumGoal(uint goal) onlyOwner public { require(goal > 0e18,"Minimum goal must be greater than 0."); minimumGoal = goal; // since we can edit the goal, we want to check if we reached the goal before in case we lowered the goal number. isGoalReached(); emit ICOConfigured(goal); } function createSale(uint numberOfTokens) onlyOwner public { require (!saleEnabled, "Sale is already going on."); require (!ICOEnded, "ICO already ended."); require (totalTokensSold < maxTokensForSale, "We already sold all our tokens."); totalTokensSoldInThisSale = 0e18; uint tryingToSell = totalTokensSold.add(numberOfTokens); // in case we are trying to create a sale with too many tokens, we subtract and sell only what&#39;s left if (tryingToSell > maxTokensForSale) { tokensForSale = maxTokensForSale.sub(totalTokensSold); } else { tokensForSale = numberOfTokens; } tryingToSell = 0e18; saleEnabled = true; emit SaleStarted(tokensForSale); } function endSale() public { if (saleEnabled) { saleEnabled = false; tokensForSale = 0e18; emit SaleEnded(); } } function endICO() onlyOwner public { if (!ICOEnded) { // run this before end of ICO and end of last sale fixTokenCalcBug(); endSale(); ICOEnded = true; lastBuyer = address(0); emit ICOHasEnded(); } } function isGoalReached() internal { // check if we reached the goal if (!wasGoalReached) { if (totalTokensSold >= minimumGoal) { wasGoalReached = true; emit GoalReached(minimumGoal); } } } function isMaxCapReached() internal { if (totalTokensSoldInThisSale >= tokensForSale) { emit SaleCapReached(totalTokensSoldInThisSale); endSale(); } if (totalTokensSold >= maxTokensForSale) { emit ICOCapReached(maxTokensForSale); endICO(); } } // This is a hack to add the lost token during final full sale. function fixTokenCalcBug() internal { require(!burned, "Fix lost token can only run before the burning of the tokens."); if (maxTokensForSale.sub(totalTokensSold) == singleToken) { totalTokensSold = totalTokensSold.add(singleToken); totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(singleToken); balances[lastBuyer] = balances[lastBuyer].add(singleToken); balances[owner] = balances[owner].sub(singleToken); emit Transfer(owner, lastBuyer, singleToken); emit OneTokenBugFixed(); } } } library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } 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 c) { c = a + b; assert(c >= a); return c; } }
Set the number of ONAs sold per ETH
function setTokensPerETH(uint newRate) onlyOwner public { require (!ICOEnded, "ICO already ended."); require (newRate > 0, "Rate must be higher than 0."); tokensPerETH = newRate; emit TokenPerETHReset(newRate); }
2,073,870
pragma solidity ^0.4.11; contract ShiyanCoin { /* 从账户地址到货币余额的映射 */ mapping (address => uint256) public balanceOf; uint256 public initialAmount; function ShiyanCoin(uint256 amount) { /* 发行货币 */ if (amount == 0) { balanceOf[msg.sender] = 300000000; } else { balanceOf[msg.sender] = amount; initialAmount = amount; } } function getInitialAmount() returns (uint256){ return initialAmount; } /* 获取账户余额 */ function getBalanceOf(address addr) returns (uint256) { return balanceOf[addr]; } /* 货币支付 */ function transfer(address _from, address _to, uint256 _value) { /* 合法性检查,支付账户余额充足,接收账户不产生溢出 */ require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); /* 支付过程 */ balanceOf[_from] -= _value; balanceOf[_to] += _value; } }
从账户地址到货币余额的映射 / 发行货币 /
function ShiyanCoin(uint256 amount) { if (amount == 0) { balanceOf[msg.sender] = 300000000; } else { balanceOf[msg.sender] = amount; initialAmount = amount; } }
12,729,225
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract Ownable { address private _owner; // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // modifier to check if caller is owner modifier onlyOwner() { // If the first argument of 'require' evaluates to 'false', execution terminates and all // changes to the state and to Ether balances are reverted. // This used to consume all gas in old EVM versions, but not anymore. // It is often a good idea to use 'require' to check if functions are called correctly. // As a second argument, you can also provide an explanation about what went wrong. require(msg.sender == _owner, "Caller is not owner"); _; } /** * @dev Set contract deployer as owner */ constructor() { _owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor emit OwnerSet(address(0), _owner); } /** * @dev Change owner * @param newOwner address of new owner */ function changeOwner(address newOwner) public onlyOwner() { emit OwnerSet(_owner, newOwner); _owner = newOwner; } /** * @dev Return owner address * @return address of owner */ function owner() public view virtual returns (address) { return _owner; } }
Change owner newOwner address of new owner/
function changeOwner(address newOwner) public onlyOwner() { emit OwnerSet(_owner, newOwner); _owner = newOwner; }
887,073
pragma ton-solidity >= 0.47.0; pragma AbiHeader time; pragma AbiHeader pubkey; pragma AbiHeader expire; //================================================================================ // import "../interfaces/ILiquidFTRoot.sol"; import "../interfaces/IParticipant.sol"; import "../interfaces/IBase.sol"; //================================================================================ // contract DepoolKeeper is IParticipant, IBase { //======================================== // Error codes uint constant ERROR_MESSAGE_SENDER_IS_NOT_ROOT = 101; uint constant ERROR_MESSAGE_SENDER_IS_NOT_DEPOOL = 102; //======================================== // Variables address static _depoolAddress; // address static _rootAddress; // uint128 _depoolFee; // uint128 _totalInvested; // uint128 _uninvestedChange; // mapping(address => uint128) _withdrawList; address[] _depoolChangeWaiters; //======================================== // Modifiers modifier onlyRoot() { require(msg.isInternal && _rootAddress != addressZero && _rootAddress == msg.sender, ERROR_MESSAGE_SENDER_IS_NOT_ROOT ); _; } modifier onlyDepool() { require(msg.isInternal && _depoolAddress != addressZero && _depoolAddress == msg.sender, ERROR_MESSAGE_SENDER_IS_NOT_DEPOOL); _; } // We don't want to spend uninvested change, but we also don't want to keep the current transaction change; modifier reserveLocal(){ tvm.rawReserve(_uninvestedChange, 0); _; } //======================================== // Getters //function getWalletCode() external view override returns (TvmCell) { return (_walletCode); } //function callWalletCode() external view responsible override reserve returns (TvmCell) { return {value: 0, flag: 128}(_walletCode); } //======================================== // constructor(uint128 depoolFee) public onlyRoot { _gasReserve = 1000000; _depoolFee = depoolFee; } //======================================== // function addOrdinaryStake(uint128 amount, address initiatorAddress) external onlyRoot { // Root ensures that we have enough to deposit, thus no checks here _totalInvested += amount; _depoolChangeWaiters.push(initiatorAddress); IDepool(_depoolAddress).addOrdinaryStake{value: amount + _depoolFee, flag: 1}(uint64(amount)); } function withdrawPart(uint128 amount, address initiatorAddress) external onlyRoot reserve reserveLocal { // Root ensures that we have enough to withdraw, thus no checks here _withdrawList[initiatorAddress] += amount; IDepool(_depoolAddress).withdrawPart{value: msg.value / 2, flag: 0}(uint64(amount)); initiatorAddress.transfer(0, false, 128); } // We can't add anything other than Ordinary Stake because TONs are like security deposit for minted tokens and all // other stake types take this security from us. //function addVestingStake (uint64 stake, address beneficiary, uint32 withdrawalPeriod, uint32 totalPeriod) //function addLockStake (uint64 stake, address beneficiary, uint32 withdrawalPeriod, uint32 totalPeriod) //function addVestingOrLock(uint64 stake, address beneficiary, uint32 withdrawalPeriod, uint32 totalPeriod, bool isVesting ) //======================================== // function onRoundComplete( uint64 roundId, uint64 reward, uint64 ordinaryStake, uint64 vestingStake, uint64 lockStake, bool reinvest, uint8 reason) external override onlyDepool { tvm.accept(); roundId; vestingStake; lockStake; reinvest; reason; // shut the warning _totalInvested += reward; // Everything more than 1 means withdrawal; // Sometimes the withdrawal can be more than we requested, for example // when stake was not enoug min_stake in depool, we need to keep that in mind; if(msg.value > 1) { _uninvestedChange += (msg.value - 1); for((address ownerAddress, uint128 desiredAmount) : _withdrawList) { if(_uninvestedChange == 0) { break; } if(_uninvestedChange >= desiredAmount) { ownerAddress.transfer(desiredAmount, false, 0); _uninvestedChange -= desiredAmount; _totalInvested -= desiredAmount; delete _withdrawList[ownerAddress]; } else { ownerAddress.transfer(_uninvestedChange, false, 0); _totalInvested -= _uninvestedChange; _uninvestedChange = 0; break; } } } tvm.rawReserve(_uninvestedChange, 0); ILiquidFTRoot(_rootAddress).onRoundComplete{value: 0, flag: 128}(_depoolAddress, uint128(ordinaryStake)); } //======================================== // function receiveAnswer(uint32 errcode, uint64 comment) external override onlyDepool reserve reserveLocal { comment; // shut the warning if(errcode == 0) { if(_depoolChangeWaiters.length > 0) { _depoolChangeWaiters[0].transfer(0, false, 128); delete _depoolChangeWaiters[0]; } } else { uint128 change = (msg.value - _depoolFee / 2); _uninvestedChange += change; tvm.rawReserve(change, 0); if(_depoolChangeWaiters.length > 0) { _depoolChangeWaiters[0].transfer(0, false, 128); delete _depoolChangeWaiters[0]; } } } //======================================== // function onTransfer(address source, uint128 amount) external override onlyDepool { source; amount; } //======================================== // receive() external { } //======================================== // } //================================================================================ //
======================================== Everything more than 1 means withdrawal; Sometimes the withdrawal can be more than we requested, for example when stake was not enoug min_stake in depool, we need to keep that in mind;
function onRoundComplete( uint64 roundId, uint64 reward, uint64 ordinaryStake, uint64 vestingStake, uint64 lockStake, bool reinvest, uint8 reason) external override onlyDepool { tvm.accept(); _totalInvested += reward; if(msg.value > 1) { _uninvestedChange += (msg.value - 1); for((address ownerAddress, uint128 desiredAmount) : _withdrawList) { if(_uninvestedChange >= desiredAmount) { ownerAddress.transfer(desiredAmount, false, 0); _uninvestedChange -= desiredAmount; _totalInvested -= desiredAmount; delete _withdrawList[ownerAddress]; } else { ownerAddress.transfer(_uninvestedChange, false, 0); _totalInvested -= _uninvestedChange; _uninvestedChange = 0; break; } } } tvm.rawReserve(_uninvestedChange, 0); }
2,540,462
./full_match/80001/0xCB881D41157ad64Fe76A0Cd0476EF3E3233d86Fe/sources/project_/contracts/IdentitiesCollection.sol
Returns whether identity was registered identityAddress - user wallet address return bool/
function isIdentityRegistered( address identityAddress ) public view override returns (bool) { return address(_wallets[identityAddress]) != address(0); }
843,495
/* Copyright 2018 CoinAlpha, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.21; import "./zeppelin/SafeMath.sol"; contract IBasketRegistry { // Called by BasketFactory function registerBasket(address, address, string, string, address[], uint[]) public returns (uint) {} function checkBasketExists (address) public returns (bool) {} function getBasketArranger (address) public returns (address) {} // Called by Basket function incrementBasketsMinted (uint, address) public returns (bool) {} function incrementBasketsBurned (uint, address) public returns (bool) {} } /** * @title BasketRegistry -- Storage contract to keep track of all baskets created * @author CoinAlpha, Inc. <[email protected]> */ contract BasketRegistry { using SafeMath for uint; // Constants set at contract inception address public admin; mapping(address => bool) public basketFactoryMap; uint public basketIndex; // Baskets index starting from index = 1 address[] public basketList; mapping(address => BasketStruct) public basketMap; mapping(address => uint) public basketIndexFromAddress; uint public arrangerIndex; // Arrangers register starting from index = 1 address[] public arrangerList; mapping(address => uint) public arrangerBasketCount; mapping(address => uint) public arrangerIndexFromAddress; // Structs struct BasketStruct { address basketAddress; address arranger; string name; string symbol; address[] tokens; uint[] weights; uint totalMinted; uint totalBurned; } // Modifiers modifier onlyBasket { require(basketIndexFromAddress[msg.sender] > 0); // Check: "Only a basket can call this function" _; } modifier onlyBasketFactory { require(basketFactoryMap[msg.sender] == true); // Check: "Only a basket factory can call this function" _; } // Events event LogWhitelistBasketFactory(address basketFactory); event LogBasketRegistration(address basketAddress, uint basketIndex); event LogIncrementBasketsMinted(address basketAddress, uint quantity, address sender); event LogIncrementBasketsBurned(address basketAddress, uint quantity, address sender); /// @dev BasketRegistry constructor function BasketRegistry() public { basketIndex = 1; arrangerIndex = 1; admin = msg.sender; } /// @dev Set basket factory address after deployment /// @param _basketFactory Basket factory address /// @return success Operation successful function whitelistBasketFactory(address _basketFactory) public returns (bool success) { require(msg.sender == admin); // Check: "Only an admin can call this function" basketFactoryMap[_basketFactory] = true; emit LogWhitelistBasketFactory(_basketFactory); return true; } /// @dev Add new basket to registry after being created in the basketFactory /// @param _basketAddress Address of deployed basket /// @param _arranger Address of basket admin /// @param _name Basket name /// @param _symbol Basket symbol /// @param _tokens Token address array /// @param _weights Weight ratio array /// @return basketIndex Index of basket in registry function registerBasket( address _basketAddress, address _arranger, string _name, string _symbol, address[] _tokens, uint[] _weights ) public onlyBasketFactory returns (uint index) { basketMap[_basketAddress] = BasketStruct( _basketAddress, _arranger, _name, _symbol, _tokens, _weights, 0, 0 ); basketList.push(_basketAddress); basketIndexFromAddress[_basketAddress] = basketIndex; if (arrangerBasketCount[_arranger] == 0) { arrangerList.push(_arranger); arrangerIndexFromAddress[_arranger] = arrangerIndex; arrangerIndex = arrangerIndex.add(1); } arrangerBasketCount[_arranger] = arrangerBasketCount[_arranger].add(1); emit LogBasketRegistration(_basketAddress, basketIndex); basketIndex = basketIndex.add(1); return basketIndex.sub(1); } /// @dev Check if basket exists in registry /// @param _basketAddress Address of basket to check /// @return basketExists function checkBasketExists(address _basketAddress) public view returns (bool basketExists) { return basketIndexFromAddress[_basketAddress] > 0; } /// @dev Retrieve basket info from the registry /// @param _basketAddress Address of basket to check /// @return basketDetails function getBasketDetails(address _basketAddress) public view returns ( address basketAddress, address arranger, string name, string symbol, address[] tokens, uint[] weights, uint totalMinted, uint totalBurned ) { BasketStruct memory b = basketMap[_basketAddress]; return (b.basketAddress, b.arranger, b.name, b.symbol, b.tokens, b.weights, b.totalMinted, b.totalBurned); } /// @dev Look up a basket's arranger /// @param _basketAddress Address of basket to check /// @return arranger function getBasketArranger(address _basketAddress) public view returns (address) { return basketMap[_basketAddress].arranger; } /// @dev Increment totalMinted from BasketStruct /// @param _quantity Quantity to increment /// @param _sender Address that bundled tokens /// @return success Operation successful function incrementBasketsMinted(uint _quantity, address _sender) public onlyBasket returns (bool) { basketMap[msg.sender].totalMinted = basketMap[msg.sender].totalMinted.add(_quantity); emit LogIncrementBasketsMinted(msg.sender, _quantity, _sender); return true; } /// @dev Increment totalBurned from BasketStruct /// @param _quantity Quantity to increment /// @param _sender Address that debundled tokens /// @return success Operation successful function incrementBasketsBurned(uint _quantity, address _sender) public onlyBasket returns (bool) { basketMap[msg.sender].totalBurned = basketMap[msg.sender].totalBurned.add(_quantity); emit LogIncrementBasketsBurned(msg.sender, _quantity, _sender); return true; } /// @dev Fallback to reject any ether sent to contract // CHeck: "BasketRegistry does not accept ETH transfers" function () public payable { revert(); } }
Look up a basket's arranger _basketAddress Address of basket to check return arranger
function getBasketArranger(address _basketAddress) public view returns (address) { return basketMap[_basketAddress].arranger; }
925,950
pragma solidity ^0.8.4; // SPDX-License-Identifier: UNLICENSED interface IBEP20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); 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); } interface IuniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } interface IuniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IuniswapV2Router01 { function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function factory() external pure returns (address); function WETH() external pure returns (address); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IuniswapV2Router02 is IuniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } /** * @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 { 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 = msg.sender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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); } } } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //MetaVault Contract ///////////// contract MetaVault is IBEP20, Ownable { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _buyLock; EnumerableSet.AddressSet private _excluded; EnumerableSet.AddressSet private _excludedFromBuyLock; EnumerableSet.AddressSet private _excludedFromStaking; //Token Info string private constant _name = 'MetaVault'; string private constant _symbol = '$MVT'; uint8 private constant _decimals = 9; uint256 public constant InitialSupply= 1000000000000 * 10**_decimals;//equals 1 000 000 000 000 tokens //Divider for the MaxBalance based on circulating Supply (1%) uint8 public constant BalanceLimitDivider=100; //Divider for sellLimit based on circulating Supply (0.1%) uint16 public constant SellLimitDivider=1000; //Buyers get locked for MaxBuyLockTime (put in seconds, works better especially if changing later) so they can't buy repeatedly uint16 public constant MaxBuyLockTime= 30; //The time Liquidity gets locked at start and prolonged once it gets released uint256 private constant DefaultLiquidityLockTime= 1800; //DevWallets address public TeamWallet=payable(0x65a89aB0402596cbDbF779dD8455B821109B6F14); address public LoanWallet=payable(0x60296fc78fcAc8937693EE0Cd6428A9324eD52Bd); //TestNet //address private constant uniswapV2Router=0xE592427A0AEce92De3Edee1F18E0157C05861564; //MainNet address private constant uniswapV2Router=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //variables that track balanceLimit and sellLimit, //can be updated based on circulating supply and Sell- and BalanceLimitDividers uint256 private _circulatingSupply =InitialSupply; uint256 public balanceLimit = _circulatingSupply; uint256 public sellLimit = _circulatingSupply; uint256 private antiWhale = 1000000000 * 10**_decimals; //Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer uint8 private _buyTax; uint8 private _sellTax; uint8 private _transferTax; uint8 private _burnTax; uint8 private _liquidityTax; uint8 private _stakingTax; //Tracks the current contract sell amount. (Not users) -- Can be updated by owner after launch to prevent massive contract sells. uint256 private _setSellAmount = 1000000000 * 10**_decimals; address private _uniswapV2PairAddress; IuniswapV2Router02 private _uniswapV2Router; //Checks if address is in Team, is needed to give Team access even if contract is renounced //Team doesn't have access to critical Functions that could turn this into a Rugpull(Exept liquidity unlocks) function _isTeam(address addr) private view returns (bool){ return addr==owner()||addr==TeamWallet||addr==LoanWallet; } //Constructor/////////// constructor () { //contract creator gets 90% of the token to create LP-Pair uint256 deployerBalance=_circulatingSupply; _balances[msg.sender] = deployerBalance; emit Transfer(address(0), msg.sender, deployerBalance); // uniswapV2 Router _uniswapV2Router = IuniswapV2Router02(uniswapV2Router); //Creates a uniswapV2 Pair _uniswapV2PairAddress = IuniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); //Sets Buy/Sell limits balanceLimit=InitialSupply/BalanceLimitDivider; sellLimit=InitialSupply/SellLimitDivider; //Sets buyLockTime buyLockTime=30; //Set Starting Tax _buyTax=10; _sellTax=10; _transferTax=10; _burnTax=0; _liquidityTax=20; _stakingTax=80; //Team wallets and deployer are excluded from Taxes _excluded.add(TeamWallet); _excluded.add(LoanWallet); _excluded.add(msg.sender); //excludes uniswapV2 Router, pair, contract and burn address from staking _excludedFromStaking.add(address(_uniswapV2Router)); _excludedFromStaking.add(_uniswapV2PairAddress); _excludedFromStaking.add(address(this)); _excludedFromStaking.add(0x000000000000000000000000000000000000dEaD); } //Transfer functionality/// //transfer function, every transfer runs through this function function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); //Manually Excluded adresses are transfering tax and lock free bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); //Transactions from and to the contract are always tax and lock free bool isContractTransfer=(sender==address(this) || recipient==address(this)); //transfers between uniswapV2Router and uniswapV2Pair are tax and lock free address uniswapV2Router=address(_uniswapV2Router); bool isLiquidityTransfer = ((sender == _uniswapV2PairAddress && recipient == uniswapV2Router) || (recipient == _uniswapV2PairAddress && sender == uniswapV2Router)); //differentiate between buy/sell/transfer to apply different taxes/restrictions bool isBuy=sender==_uniswapV2PairAddress|| sender == uniswapV2Router; bool isSell=recipient==_uniswapV2PairAddress|| recipient == uniswapV2Router; //Pick transfer if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ //once trading is enabled, it can't be turned off again require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } //applies taxes, checks for limits, locks generates autoLP and stakingETH, and autostakes function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ //Sells can't exceed the sell limit(21,000 Tokens at start, can be updated to circulating supply) require(amount<=sellLimit,"Dump protection"); tax=_sellTax; } else if(isBuy){ if(!_excludedFromBuyLock.contains(recipient)){ //If buyer bought less than buyLockTime(2h 50m) ago, buy is declined, can be disabled by Team require(_buyLock[recipient]<=block.timestamp||buyLockDisabled,"Buyer in buyLock"); //Sets the time buyers get locked(2 hours 50 mins by default) _buyLock[recipient]=block.timestamp+buyLockTime; } //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); require(amount <= antiWhale,"Tx amount exceeding max buy amount"); tax=_buyTax; } else {//Transfer //withdraws ETH when sending less or equal to 1 Token //that way you can withdraw without connecting to any dApp. //might needs higher gas limit if(amount<=10**(_decimals)) claimBTC(sender); //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); tax=_transferTax; } //Swapping AutoLP and MarketingETH is only possible if sender is not uniswapV2 pair, //if its not manually disabled, if its not already swapping and if its a Sell to avoid // people from causing a large price impact from repeatedly transfering when theres a large backlog of Tokens if((sender!=_uniswapV2PairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier)&&isSell) _swapContractToken(); //Calculates the exact token amount for each tax uint256 tokensToBeBurnt=_calculateFee(amount, tax, _burnTax); //staking and liquidity Tax get treated the same, only during conversion they get split uint256 contractToken=_calculateFee(amount, tax, _stakingTax+_liquidityTax); //Subtract the Taxed Tokens from the amount uint256 taxedAmount=amount-(tokensToBeBurnt + contractToken); //Removes token and handles staking _removeToken(sender,amount); //Adds the taxed tokens to the contract wallet _balances[address(this)] += contractToken; //Burns tokens _circulatingSupply-=tokensToBeBurnt; //Adds token and handles staking _addToken(recipient, taxedAmount); emit Transfer(sender,recipient,taxedAmount); } //Feeless transfer only transfers and autostakes function _feelessTransfer(address sender, address recipient, uint256 amount) private{ uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); //Removes token and handles staking _removeToken(sender,amount); //Adds token and handles staking _addToken(recipient, amount); emit Transfer(sender,recipient,amount); } //Calculates the token that should be taxed function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) { return (amount*tax*taxPercent) / 10000; } //ETH Autostake///////////////////////////////////////////////////////////////////////////////////////// //Autostake uses the balances of each holder to redistribute auto generated ETH. //Each transaction _addToken and _removeToken gets called for the transaction amount //WithdrawETH can be used for any holder to withdraw ETH at any time, like true Staking, //so unlike MRAT clones you can leave and forget your Token and claim after a while //lock for the withdraw bool private _isWithdrawing; //Multiplier to add some accuracy to profitPerShare uint256 private constant DistributionMultiplier = 2**64; //profit for each share a holder holds, a share equals a token. uint256 public profitPerShare; //the total reward distributed through staking, for tracking purposes uint256 public totalStakingReward; //the total payout through staking, for tracking purposes uint256 public totalPayouts; //marketing share starts at 50% //its capped to 50% max, the percentage of the staking that gets used for //marketing/paying the team uint8 public StakingShare=50; //balance that is claimable by the team uint256 public marketingBalance; //Mapping of the already paid out(or missed) shares of each staker mapping(address => uint256) private alreadyPaidShares; //Mapping of shares that are reserved for payout mapping(address => uint256) private toBePaid; //Contract, uniswapV2 and burnAddress are excluded, other addresses like CEX //can be manually excluded, excluded list is limited to 30 entries to avoid a //out of gas exeption during sells function isExcludedFromStaking(address addr) public view returns (bool){ return _excludedFromStaking.contains(addr); } //Total shares equals circulating supply minus excluded Balances function _getTotalShares() public view returns (uint256){ uint256 shares=_circulatingSupply; //substracts all excluded from shares, excluded list is limited to 30 // to avoid creating a Honeypot through OutOfGas exeption for(uint i=0; i<_excludedFromStaking.length(); i++){ shares-=_balances[_excludedFromStaking.at(i)]; } return shares; } //adds Token to balances, adds new ETH to the toBePaid mapping and resets staking function _addToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]+amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } //gets the payout before the change uint256 payment=_newDividentsOf(addr); //resets dividents to 0 for newAmount alreadyPaidShares[addr] = profitPerShare * newAmount; //adds dividents to the toBePaid mapping toBePaid[addr]+=payment; //sets newBalance _balances[addr]=newAmount; } //removes Token, adds ETH to the toBePaid mapping and resets staking function _removeToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]-amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } //gets the payout before the change uint256 payment=_newDividentsOf(addr); //sets newBalance _balances[addr]=newAmount; //resets dividents to 0 for newAmount alreadyPaidShares[addr] = profitPerShare * newAmount; //adds dividents to the toBePaid mapping toBePaid[addr]+=payment; } //gets the not dividents of a staker that aren't in the toBePaid mapping //returns wrong value for excluded accounts function _newDividentsOf(address staker) private view returns (uint256) { uint256 fullPayout = profitPerShare * _balances[staker]; // if theres an overflow for some unexpected reason, return 0, instead of // an exeption to still make trades possible if(fullPayout<alreadyPaidShares[staker]) return 0; return (fullPayout - alreadyPaidShares[staker]) / DistributionMultiplier; } //distributes ETH between marketing share and dividends function _distributeStake(uint256 ETHAmount) private { // Deduct marketing Tax uint256 marketingSplit = (ETHAmount * StakingShare) / 100; uint256 amount = ETHAmount - marketingSplit; marketingBalance+=marketingSplit; if (amount > 0) { totalStakingReward += amount; uint256 totalShares=_getTotalShares(); //when there are 0 shares, add everything to marketing budget if (totalShares == 0) { marketingBalance += amount; }else{ //Increases profit per share based on current total shares profitPerShare += ((amount * DistributionMultiplier) / totalShares); } } } event OnWithdrawBTC(uint256 amount, address recipient); //withdraws all dividents of address function claimBTC(address addr) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ //if excluded just withdraw remaining toBePaid ETH amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); //sets payout mapping to current amount alreadyPaidShares[addr] = profitPerShare * _balances[addr]; //the amount to be paid amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } if(amount==0){//no withdraw if 0 amount _isWithdrawing=false; return; } totalPayouts+=amount; address[] memory path = new address[](2); path[0] = _uniswapV2Router.WETH(); //WETH path[1] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //WETH _uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, path, addr, block.timestamp); emit OnWithdrawBTC(amount, addr); _isWithdrawing=false; } //Swap Contract Tokens////////////////////////////////////////////////////////////////////////////////// //tracks auto generated ETH, useful for ticker etc uint256 public totalLPETH; //Locks the swap if already swapping bool private _isSwappingContractModifier; modifier lockTheSwap { _isSwappingContractModifier = true; _; _isSwappingContractModifier = false; } //swaps the token on the contract for Marketing ETH and LP Token. //always swaps the sellLimit of token to avoid a large price impact function _swapContractToken() private lockTheSwap{ uint256 contractBalance=_balances[address(this)]; uint16 totalTax=_liquidityTax+_stakingTax; uint256 tokenToSwap = _setSellAmount; //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0 if(contractBalance<tokenToSwap||totalTax==0){ return; } //splits the token in TokenForLiquidity and tokenForMarketing uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax; uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity; //splits tokenForLiquidity in 2 halves uint256 liqToken=tokenForLiquidity/2; uint256 liqETHToken=tokenForLiquidity-liqToken; //swaps marktetingToken and the liquidity token half for ETH uint256 swapToken=liqETHToken+tokenForMarketing; //Gets the initial ETH balance, so swap won't touch any staked ETH uint256 initialETHBalance = address(this).balance; _swapTokenForETH(swapToken); uint256 newETH=(address(this).balance - initialETHBalance); //calculates the amount of ETH belonging to the LP-Pair and converts them to LP uint256 liqETH = (newETH*liqETHToken)/swapToken; _addLiquidity(liqToken, liqETH); //Get the ETH balance after LP generation to get the //exact amount of token left for Staking uint256 distributeETH=(address(this).balance - initialETHBalance); //distributes remaining ETH between stakers and Marketing _distributeStake(distributeETH); } //swaps tokens on the contract for ETH function _swapTokenForETH(uint256 amount) private { _approve(address(this), address(_uniswapV2Router), amount); address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); } //Adds Liquidity directly to the contract where LP are locked(unlike safemoon forks, that transfer it to the owner) function _addLiquidity(uint256 tokenamount, uint256 ETHamount) private { totalLPETH=ETHamount; _approve(address(this), address(_uniswapV2Router), tokenamount); _uniswapV2Router.addLiquidityETH{value: ETHamount}( address(this), tokenamount, 0, 0, address(this), block.timestamp ); } //public functions ///////////////////////////////////////////////////////////////////////////////////// function getLiquidityReleaseTimeInSeconds() public view returns (uint256){ if(block.timestamp<_liquidityUnlockTime){ return _liquidityUnlockTime-block.timestamp; } return 0; } function getBurnedTokens() public view returns(uint256){ return (InitialSupply-_circulatingSupply)/10**_decimals; } function getLimits() public view returns(uint256 balance, uint256 sell){ return(balanceLimit/10**_decimals, sellLimit/10**_decimals); } function getTaxes() public view returns(uint256 burnTax,uint256 liquidityTax,uint256 marketingTax, uint256 buyTax, uint256 sellTax, uint256 transferTax){ return (_burnTax,_liquidityTax,_stakingTax,_buyTax,_sellTax,_transferTax); } //How long is a given address still locked from buying function getAddressBuyLockTimeInSeconds(address AddressToCheck) public view returns (uint256){ uint256 lockTime=_buyLock[AddressToCheck]; if(lockTime<=block.timestamp) { return 0; } return lockTime-block.timestamp; } function getBuyLockTimeInSeconds() public view returns(uint256){ return buyLockTime; } //Functions every wallet can call //Resets buy lock of caller to the default buyLockTime should something go very wrong function AddressResetBuyLock() public{ _buyLock[msg.sender]=block.timestamp+buyLockTime; } function getDividents(address addr) public view returns (uint256){ if(isExcludedFromStaking(addr)) return toBePaid[addr]; return _newDividentsOf(addr)+toBePaid[addr]; } //Settings////////////////////////////////////////////////////////////////////////////////////////////// bool public buyLockDisabled; uint256 public buyLockTime; bool public manualConversion; function TeamWithdrawALLMarketingETH() public onlyOwner{ uint256 amount=marketingBalance; marketingBalance=0; payable(TeamWallet).transfer(amount*3/4); payable(LoanWallet).transfer(amount*1/4); } function TeamWithdrawXMarketingETH(uint256 amount) public onlyOwner{ require(amount<=marketingBalance); marketingBalance-=amount; payable(TeamWallet).transfer(amount*3/4); payable(LoanWallet).transfer(amount*1/4); } //switches autoLiquidity and marketing ETH generation during transfers function TeamSwitchManualETHConversion(bool manual) public onlyOwner{ manualConversion=manual; } function TeamChangeAntiWhale(uint256 newAntiWhale) public onlyOwner{ antiWhale=newAntiWhale * 10**_decimals; } function TeamChangeTeamWallet(address newTeamWallet) public onlyOwner{ TeamWallet=payable(newTeamWallet); } function TeamChangeLoanWallet(address newLoanWallet) public onlyOwner{ LoanWallet=payable(newLoanWallet); } //Disables the timeLock after buying for everyone function TeamDisableBuyLock(bool disabled) public onlyOwner{ buyLockDisabled=disabled; } //Sets BuyLockTime, needs to be lower than MaxBuyLockTime function TeamSetBuyLockTime(uint256 buyLockSeconds)public onlyOwner{ require(buyLockSeconds<=MaxBuyLockTime,"Buy Lock time too high"); buyLockTime=buyLockSeconds; } //Allows wallet exclusion to be added after launch function AddWalletExclusion(address exclusionAdd) public onlyOwner{ _excluded.add(exclusionAdd); } //Sets Taxes, is limited by MaxTax(20%) to make it impossible to create honeypot function TeamSetTaxes(uint8 burnTaxes, uint8 liquidityTaxes, uint8 stakingTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyOwner{ uint8 totalTax=burnTaxes+liquidityTaxes+stakingTaxes; require(totalTax==100, "burn+liq+marketing needs to equal 100%"); _burnTax=burnTaxes; _liquidityTax=liquidityTaxes; _stakingTax=stakingTaxes; _buyTax=buyTax; _sellTax=sellTax; _transferTax=transferTax; } //How much of the staking tax should be allocated for marketing function TeamChangeStakingShare(uint8 newShare) public onlyOwner{ require(newShare<=50); StakingShare=newShare; } //manually converts contract token to LP and staking ETH function TeamCreateLPandETH() public onlyOwner{ _swapContractToken(); } //Limits need to be at least target, to avoid setting value to 0(avoid potential Honeypot) function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyOwner{ //SellLimit needs to be below 1% to avoid a Large Price impact when generating auto LP require(newSellLimit<_circulatingSupply/100); //Adds decimals to limits newBalanceLimit=newBalanceLimit*10**_decimals; newSellLimit=newSellLimit*10**_decimals; //Calculates the target Limits based on supply uint256 targetBalanceLimit=_circulatingSupply/BalanceLimitDivider; uint256 targetSellLimit=_circulatingSupply/SellLimitDivider; require((newBalanceLimit>=targetBalanceLimit), "newBalanceLimit needs to be at least target"); require((newSellLimit>=targetSellLimit), "newSellLimit needs to be at least target"); balanceLimit = newBalanceLimit; sellLimit = newSellLimit; } //Setup Functions/////////////////////////////////////////////////////////////////////////////////////// bool public tradingEnabled; address private _liquidityTokenAddress; //Enables trading for everyone function SetupEnableTrading() public onlyOwner{ tradingEnabled=true; } //Sets up the LP-Token Address required for LP Release function SetupLiquidityTokenAddress(address liquidityTokenAddress) public onlyOwner{ _liquidityTokenAddress=liquidityTokenAddress; } //Contract TokenToSwap change function. function changeTokenToSwapAmount(uint256 _setAmountToSwap) public onlyOwner { _setSellAmount = _setAmountToSwap; } //Liquidity Lock//////////////////////////////////////////////////////////////////////////////////////// //the timestamp when Liquidity unlocks uint256 private _liquidityUnlockTime; function TeamUnlockLiquidityInSeconds(uint256 secondsUntilUnlock) public onlyOwner{ _prolongLiquidityLock(secondsUntilUnlock+block.timestamp); } function _prolongLiquidityLock(uint256 newUnlockTime) private{ // require new unlock time to be longer than old one require(newUnlockTime>_liquidityUnlockTime); _liquidityUnlockTime=newUnlockTime; } //Release Liquidity Tokens once unlock time is over function TeamReleaseLiquidity() public onlyOwner { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); //Liquidity release if something goes wrong at start liquidityToken.transfer(TeamWallet, amount); } //Removes Liquidity once unlock Time is over, function TeamRemoveLiquidity(bool addToStaking) public onlyOwner{ //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); liquidityToken.approve(address(_uniswapV2Router),amount); //Removes Liquidity and either distributes liquidity ETH to stakers, or // adds them to marketing Balance //Token will be converted //to Liquidity and Staking ETH again uint256 initialETHBalance = address(this).balance; _uniswapV2Router.removeLiquidityETHSupportingFeeOnTransferTokens( address(this), amount, 0, 0, address(this), block.timestamp ); uint256 newETHBalance = address(this).balance-initialETHBalance; if(addToStaking){ _distributeStake(newETHBalance); } else{ marketingBalance+=newETHBalance; } } //Releases all remaining ETH on the contract wallet, so ETH wont be burned function TeamRemoveRemainingETH() public onlyOwner{ require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; (bool sent,) =TeamWallet.call{value: (address(this).balance)}(""); require(sent); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //external////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// receive() external payable {} fallback() external payable {} // IBEP20 function getOwner() external view override returns (address) { return owner(); } function name() external pure override returns (string memory) { return _name; } function symbol() external pure override returns (string memory) { return _symbol; } function decimals() external pure override returns (uint8) { return _decimals; } function totalSupply() external view override returns (uint256) { return _circulatingSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address _owner, address spender) external view override returns (uint256) { return _allowances[_owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "Approve from zero"); require(spender != address(0), "Approve to zero"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "Transfer > allowance"); _approve(sender, msg.sender, currentAllowance - amount); return true; } // IBEP20 - Helpers function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "<0 allowance"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } }
Sets BuyLockTime, needs to be lower than MaxBuyLockTime
function TeamSetBuyLockTime(uint256 buyLockSeconds)public onlyOwner{ require(buyLockSeconds<=MaxBuyLockTime,"Buy Lock time too high"); buyLockTime=buyLockSeconds; }
965,474
pragma solidity ^0.5.0; import "../util/Authorizable.sol"; import "../ProxyToken/ProxyToken.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title ProxyTokenRequestsStorageV0 */ contract ProxyTokenRequestsStorageV0 is Authorizable { using SafeMath for uint256; enum Status { NEW, FULFILLED, CANCELLED, REJECTED } /** * @notice MintRequest organizes data for requests involving token minting * @param status the status of the request * @param mintID the id of the request * @param addressMap String to address mapping * @param uintMap String to uint256 mapping * @param stringMap String to string mapping */ struct MintRequest { Status status; uint256 mintID; mapping (string => address) addressMap; mapping (string => uint256) uintMap; mapping (string => string) stringMap; } /** * @notice BurnRequest organizes data for requests involving token burning * @param status the status of the request * @param burnID the id of the request * @param addressMap String to address mapping * @param uintMap String to uint256 mapping * @param stringMap String to string mapping */ struct BurnRequest { Status status; uint256 burnID; mapping (string => address) addressMap; mapping (string => uint256) uintMap; mapping (string => string) stringMap; } MintRequest[] public mintRequests; BurnRequest[] public burnRequests; /** * @notice Constructor for the ProxyTokenRequestsStorageV0 * @param owner address of owner */ constructor(address owner) public Authorizable(owner) {} // solium-disable-line no-empty-blocks /** * @dev Runs a function only after checking if the requestId * is a valid burn request * @param requestId Identification for burn request */ modifier onlyValidBurnRequest(uint256 requestId) { require(requestId < burnRequests.length, "Not a valid burn request ID"); _; } /** * @dev Runs a function only after checking if the requestId * is a valid mint request * @param requestId Identification for mint request */ modifier onlyValidMintRequest(uint256 requestId) { require(requestId < mintRequests.length, "Not a valid mint request ID"); _; } /** * @notice Initialize a mint request */ function createMintRequest() public isAuthorized(msg.sender) returns (uint256) { uint256 requestId = mintRequests.length; mintRequests.push(MintRequest(Status.NEW, requestId)); return requestId; } /** * @notice Initialize a burn request */ function createBurnRequest() public isAuthorized(msg.sender) returns (uint256) { uint256 requestId = burnRequests.length; burnRequests.push(BurnRequest(Status.NEW, requestId)); return requestId; } /** * @notice Get the burn requests array length */ function getBurnRequestsLength() public view returns(uint256) { return burnRequests.length; } /** * @notice Get the mint requests array length */ function getMintRequestsLength() public view returns(uint256) { return mintRequests.length; } /** * @notice Return a mintRequest status * @param mintRequestID mintRequestID of mint request */ function getMintRequestStatus( uint256 mintRequestID) public onlyValidMintRequest(mintRequestID) view returns (Status) { MintRequest storage request = mintRequests[mintRequestID]; return request.status; } /** * @notice Return a burnRequest status * @param burnRequestID burnRequestID of burn request */ function getBurnRequestStatus( uint256 burnRequestID) public onlyValidBurnRequest(burnRequestID) view returns (Status) { BurnRequest storage request = burnRequests[burnRequestID]; return request.status; } /** * @notice Get a mintRequest's addressMap value with a specific key * @param mintRequestID mintRequestID of mint request to return * @param key Key value for addressMap */ function getMintRequestAddressMap( uint256 mintRequestID, string memory key) public onlyValidMintRequest(mintRequestID) view returns (address) { MintRequest storage request = mintRequests[mintRequestID]; return request.addressMap[key]; } /** * @notice Get a burnRequest's addressMap value with a specific key * @param burnRequestID burnRequestID of mint request to return * @param key Key value for addressMap */ function getBurnRequestAddressMap( uint256 burnRequestID, string memory key) public onlyValidBurnRequest(burnRequestID) view returns (address) { BurnRequest storage request = burnRequests[burnRequestID]; return request.addressMap[key]; } /** * @notice Get a mintRequest's uintMap value with a specific key * @param mintRequestID mintRequestID of mint request to return * @param key Key value for uintMap */ function getMintRequestUintMap( uint256 mintRequestID, string memory key) public onlyValidMintRequest(mintRequestID) view returns (uint256) { MintRequest storage request = mintRequests[mintRequestID]; return request.uintMap[key]; } /** * @notice Get a burnRequest's uintMap value with a specific key * @param burnRequestID burnRequestID of mint request to return * @param key Key value for uintMap */ function getBurnRequestUintMap( uint256 burnRequestID, string memory key) public onlyValidBurnRequest(burnRequestID) view returns (uint256) { BurnRequest storage request = burnRequests[burnRequestID]; return request.uintMap[key]; } /** * @notice Get a mintRequest's stringMap value with a specific key * @param mintRequestID mintRequestID of mint request to return * @param key Key value for stringMap */ function getMintRequestStringMap( uint256 mintRequestID, string memory key) public onlyValidMintRequest(mintRequestID) view returns (string memory) { MintRequest storage request = mintRequests[mintRequestID]; return request.stringMap[key]; } /** * @notice Get a burnRequest's stringMap value with a specific key * @param burnRequestID burnRequestID of mint request to return * @param key Key value for stringMap */ function getBurnRequestStringMap( uint256 burnRequestID, string memory key) public onlyValidBurnRequest(burnRequestID) view returns (string memory) { BurnRequest storage request = burnRequests[burnRequestID]; return request.stringMap[key]; } /** * @notice Modify a mintRequest status * @param mintRequestID mintRequestID of mint request to modify * @param newStatus New status to be set */ function setMintRequestStatus( uint256 mintRequestID, Status newStatus) public isAuthorized(msg.sender) onlyValidMintRequest(mintRequestID) { MintRequest storage request = mintRequests[mintRequestID]; request.status = newStatus; } /** * @notice Modify a burnRequest status * @param burnRequestID burnRequestID of burn request to modify * @param newStatus New status to be set */ function setBurnRequestStatus( uint256 burnRequestID, Status newStatus) public isAuthorized(msg.sender) onlyValidBurnRequest(burnRequestID) { BurnRequest storage request = burnRequests[burnRequestID]; request.status = newStatus; } /** * @notice Modify a mintRequest's addressMap with a specific key pair * @param mintRequestID mintRequestID of mint request to modify * @param key Key value for addressMap * @param value Value addressMap[key] will be changed to */ function setMintRequestAddressMap( uint256 mintRequestID, string memory key, address value) public isAuthorized(msg.sender) onlyValidMintRequest(mintRequestID) { MintRequest storage request = mintRequests[mintRequestID]; request.addressMap[key] = value; } /** * @notice Modify a burnRequest's addressMap with a specific key pair * @param burnRequestID burnRequestID of burn request to modify * @param key Key value for addressMap * @param value Value addressMap[key] will be changed to */ function setBurnRequestAddressMap( uint256 burnRequestID, string memory key, address value) public isAuthorized(msg.sender) onlyValidBurnRequest(burnRequestID) { BurnRequest storage request = burnRequests[burnRequestID]; request.addressMap[key] = value; } /** * @notice Modify a mintRequest's uintMap with a specific key pair * @param mintRequestID mintRequestID of mint request to modify * @param key Key value for uintMap * @param value Value uintMap[key] will be changed to */ function setMintRequestUintMap( uint256 mintRequestID, string memory key, uint value) public isAuthorized(msg.sender) onlyValidMintRequest(mintRequestID) { MintRequest storage request = mintRequests[mintRequestID]; request.uintMap[key] = value; } /** * @notice Modify a burnRequest's uintMap with a specific key pair * @param burnRequestID burnRequestID of burn request to modify * @param key Key value for uintMap * @param value Value uintMap[key] will be changed to */ function setBurnRequestUintMap( uint256 burnRequestID, string memory key, uint value) public isAuthorized(msg.sender) onlyValidBurnRequest(burnRequestID) { BurnRequest storage request = burnRequests[burnRequestID]; request.uintMap[key] = value; } /** * @notice Modify a mintRequest's stringMap with a specific key pair * @param mintRequestID mintRequestID of mint request to modify * @param key Key value for stringMap * @param value Value stringMap[key] will be changed to */ function setMintRequestStringMap( uint256 mintRequestID, string memory key, string memory value) public isAuthorized(msg.sender) onlyValidMintRequest(mintRequestID) { MintRequest storage request = mintRequests[mintRequestID]; request.stringMap[key] = value; } /** * @notice Modify a burnRequest's stringMap with a specific key pair * @param burnRequestID burnRequestID of burn request to modify * @param key Key value for stringMap * @param value Value stringMap[key] will be changed to */ function setBurnRequestStringMap( uint256 burnRequestID, string memory key, string memory value) public isAuthorized(msg.sender) onlyValidBurnRequest(burnRequestID) { BurnRequest storage request = burnRequests[burnRequestID]; request.stringMap[key] = value; } }
Get a burnRequest's uintMap value with a specific key burnRequestID burnRequestID of mint request to return key Key value for uintMap/
function getBurnRequestUintMap( uint256 burnRequestID, string memory key) public onlyValidBurnRequest(burnRequestID) view returns (uint256) { BurnRequest storage request = burnRequests[burnRequestID]; return request.uintMap[key]; }
5,449,329
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; import "./DigitalContentSpec.sol"; import "./SafeMath.sol"; /// @title RightsDigitalConentObject contract DigitalContentObject is DigitalContentSpec { using SafeMath for uint; /*** DATA TYPES ***/ struct DigitalContentObject { uint256 specId; // content spec id string mediaId; // media file id string info; //content's additional information } /*** STORAGE ***/ DigitalContentObject[] private digitalContentObjects; // all object list (this index is objectId) // Mapping from object ID to owner mapping (uint256 => address) private _objectOwner; // Mapping from object ID to approved address mapping (uint256 => address) private _objectApprovals; // Mapping from owner to list of owned object IDs mapping(address => uint256[]) private _ownedObjects; // Mapping from owner to number of owned object mapping (address => uint256) private _ownedObjectsCount; // Mapping from spec ID to index of the minted objects list mapping(uint256 => uint256[]) private mintedObjects; // Mapping from object id to position in the minted objects array mapping(uint256 => uint256) private mintedObjectsIndex; // Array with all object ids, used for enumeration uint256[] private _allObjects; /*** Event ***/ event MintLog( address owner, uint256 objectId, string mediaId, string info, uint256 specId ); event SetMediaIdLog( address owner, uint256 objectId, string mediaId ); event TransferLog( address from, address to, uint256 objectId ); event ApprovalLog( address owner, address to, uint256 objectId ); event SetInfoLog( address owner, uint256 objectId, string info ); /*** EXTERNAL FUNCTIONS ***/ /** * @dev Mint a DigitalContent. * @param _to The address that will own the minted object * @param _specId spec identifer * @param _mediaId mediaId * @param _info info */ function mint( address _to, uint256 _specId, string memory _mediaId, string memory _info ) public whenNotPaused { require(specOwnerOf(_specId) == msg.sender); // check total supply count require( totalSupplyLimitOf(_specId) >= mintedObjects[_specId].length || totalSupplyLimitOf(_specId) == 0 ); require( keccak256(abi.encodePacked(_mediaId)) == keccak256(abi.encodePacked(mediaIdOf(_specId))) ); DigitalContentObject memory digitalContentObject = DigitalContentObject({ specId : _specId, mediaId: _mediaId, info: _info }); digitalContentObjects.push(digitalContentObject); uint256 objectId = digitalContentObjects.length.sub(1); _mint(_to, objectId); _addObjectTo(_specId, objectId); emit MintLog( _to, objectId, _mediaId, _info, digitalContentObject.specId ); } /** * @dev Set MediaId * @param _objectId object identifer * @param _mediaId mediaId */ function setMediaId(uint256 _objectId, string memory _mediaId) public whenNotPaused { require(_objectExists(_objectId)); DigitalContentObject storage digitalContent = digitalContentObjects[_objectId]; require(specOwnerOf(digitalContent.specId) == msg.sender); require(keccak256(abi.encodePacked(digitalContent.mediaId)) == keccak256(abi.encodePacked(""))); // set mediaId digitalContent.mediaId = _mediaId; emit SetMediaIdLog(msg.sender, _objectId, digitalContent.mediaId); } function setInfo(uint256 _objectId, string memory _info) public whenNotPaused { require(_objectExists(_objectId)); DigitalContentObject storage digitalContent = digitalContentObjects[_objectId]; require(objectOwnerOf(_objectId) == msg.sender); // set digitalContent.info = _info; emit SetInfoLog(msg.sender, _objectId, digitalContent.info); } /** * @dev Get DigitalContent. * @param _objectId object identifer * @return objectId object id * @return specId spec id * @return mediaId media id * @return info info * @return owner owner address * @return objectIndex object index */ function getDigitalContentObject(uint256 _objectId) public view returns ( uint256 objectId, uint256 specId, string memory mediaId, string memory info, address owner, uint256 objectIndex ) { require(_objectExists(_objectId)); DigitalContentObject storage digitalContent = digitalContentObjects[_objectId]; address objectOwner = objectOwnerOf(_objectId); return ( _objectId, digitalContent.specId, digitalContent.mediaId, digitalContent.info, objectOwner, mintedObjectsIndex[_objectId] ); } /** * @dev Get specId of DigitalContent. * @param _objectId object identifer * @return specId */ function specIdOf(uint256 _objectId) public view returns (uint256) { require(_objectExists(_objectId)); return digitalContentObjects[_objectId].specId; } /** * @dev Get mediaId of DigitalContent. * @param _objectId object identifer * @return mediaId */ function objectMediaIdOf(uint256 _objectId) public view returns (string memory) { require(_objectExists(_objectId)); return digitalContentObjects[_objectId].mediaId; } /** * @dev Get info of DigitalContent. * @param _objectId object identifer * @return info */ function objectInfoOf(uint256 _objectId) public view returns (string memory) { require(_objectExists(_objectId)); return digitalContentObjects[_objectId].info; } /** * @dev Gets the total amount of objects stored by the contract per spec * @param _specId spec identifer * @return uint256 representing the total amount of objects per spec */ function totalSupplyOf(uint256 _specId) public view returns (uint256) { require(specOwnerOf(_specId) != address(0)); return mintedObjects[_specId].length; } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function objectBalanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedObjectsCount[owner]; } /** * @dev Get objectIndex of DigitalContent. * @param _objectId object identifer * @return objectIndex */ function objectIndexOf(uint256 _objectId) public view returns (uint256) { require(_objectExists(_objectId)); return mintedObjectsIndex[_objectId]; } /** * @dev Gets the owner of the specified object ID. * @param _objectId uint256 ID of the object to query the owner of * @return address currently marked as the owner of the given object ID */ function objectOwnerOf(uint256 _objectId) public view returns (address) { address owner = _objectOwner[_objectId]; require(owner != address(0), "ERC721: owner query for nonexistent object"); return owner; } /** * @dev Transfers the ownership of a given object ID to another address. * @param _to address to receive the ownership of the given object ID * @param _objectId uint256 ID of the object to be transferred */ function transfer(address _to, uint256 _objectId) public { _transfer(msg.sender, _to, _objectId); } /** * @dev Transfers the ownership of a given object ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param _from current owner of the object * @param _to address to receive the ownership of the given object ID * @param _objectId uint256 ID of the object to be transferred */ function transferFrom(address _from, address _to, uint256 _objectId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, _objectId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(_from, _to, _objectId); } /** * @dev Approves another address to transfer the given object ID * The zero address indicates there is no approved address. * There can only be one approved address per object at a given time. * Can only be called by the object owner or an approved operator. * @param to address to be approved for the given object ID * @param _objectId uint256 ID of the object to be approved */ function approve(address to, uint256 _objectId) public { address owner = objectOwnerOf(_objectId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner, "ERC721: approve caller is not owner nor approved for all" ); _objectApprovals[_objectId] = to; emit ApprovalLog(owner, to, _objectId); } /** * @dev Gets the approved address for a object ID, or zero if no address set * Reverts if the object ID does not exist. * @param _objectId uint256 ID of the object to query the approval of * @return address currently approved for the given object ID */ function getApproved(uint256 _objectId) public view returns (address) { require(_objectExists(_objectId), "ERC721: approved query for nonexistent object"); return _objectApprovals[_objectId]; } /*** INTERNAL FUNCTIONS ***/ /** * @dev Internal function to mint a new object. * Reverts if the given object ID already exists. * @param _to address the beneficiary that will own the minted object * @param _objectId uint256 ID of the object to be minted */ function _mint(address _to, uint256 _objectId) internal { _ownedObjects[_to].push(_objectId); _objectOwner[_objectId] = _to; _ownedObjectsCount[_to] += 1; } /** * @dev Internal function to add a object ID to the list of the spec * @param _specId uint256 ID of the spec * @param _objectId uint256 ID of the object to be added to the objects list of the given address */ function _addObjectTo(uint256 _specId, uint256 _objectId) internal { mintedObjects[_specId].push(_objectId); mintedObjectsIndex[_objectId] = mintedObjects[_specId].length; } /** * @dev Internal function to transfer ownership of a given object ID to another address. * @param _to address to receive the ownership of the given object ID * @param _objectId uint256 ID of the object to be transferred */ function _transfer(address _sender, address _to, uint256 _objectId) internal { require(objectOwnerOf(_objectId) == _sender, "ERC721: transfer of object that is not own"); require(_to != address(0), "ERC721: transfer to the zero address"); _clearApproval(_objectId); _ownedObjectsCount[_sender] -= 1; _ownedObjectsCount[_to] += 1; _objectOwner[_objectId] = _to; emit TransferLog(_sender, _to, _objectId); } /** * @dev Internal function to transfer ownership of a given object ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param _from current owner of the object * @param _to address to receive the ownership of the given object ID * @param _objectId uint256 ID of the object to be transferred */ function _transferFrom(address _from, address _to, uint256 _objectId) internal { require(objectOwnerOf(_objectId) == _from, "ERC721: transfer of object that is not own"); require(_to != address(0), "ERC721: transfer to the zero address"); _clearApproval(_objectId); _ownedObjectsCount[_from] -= 1; _ownedObjectsCount[_to] += 1; _objectOwner[_objectId] = _to; emit TransferLog(_from, _to, _objectId); } /** * @dev Returns whether the given spender can transfer a given object ID. * @param _spender address of the spender to query * @param _objectId uint256 ID of the object to be transferred * @return bool whether the msg.sender is approved for the given object ID, * is an operator of the owner, or is the owner of the object */ function _isApprovedOrOwner(address _spender, uint256 _objectId) internal view returns (bool) { require(_objectExists(_objectId), "ERC721: operator query for nonexistent object"); address owner = objectOwnerOf(_objectId); return (_spender == owner || getApproved(_objectId) == _spender); } /** * @dev Private function to confirm exist of a agiven object ID. * @param _objectId uint256 ID of the object */ function _objectExists(uint256 _objectId) internal view returns (bool) { if (objectOwnerOf(_objectId) != address(0)) { return true; } } /** * @dev Private function to clear current approval of a given object ID. * @param _objectId uint256 ID of the object to be transferred */ function _clearApproval(uint256 _objectId) private { if (_objectApprovals[_objectId] != address(0)) { _objectApprovals[_objectId] = address(0); } } }
Get info of DigitalContent. _objectId object identifer return info/
function objectInfoOf(uint256 _objectId) public view returns (string memory) { require(_objectExists(_objectId)); return digitalContentObjects[_objectId].info; }
13,000,844
// SPDX-License-Identifier: MIT /** * @authors: [@unknownunknown1, @jaybuidl] * @reviewers: [] * @auditors: [] * @bounties: [] * @deployments: [] */ pragma solidity ^0.8; import "./BaseDisputeKit.sol"; import "../../rng/RNG.sol"; interface IProofOfHumanity { /** @dev Return true if the submission is registered and not expired. * @param _submissionID The address of the submission. * @return Whether the submission is registered or not. */ function isRegistered(address _submissionID) external view returns (bool); } /** * @title DisputeKitSybilResistant * Dispute kit implementation adapted from DisputeKitClassic * - a drawing system: at most 1 vote per juror registered on Proof of Humanity, * - a vote aggreation system: plurality, * - an incentive system: equal split between coherent votes, * - an appeal system: fund 2 choices only, vote on any choice. */ contract DisputeKitSybilResistant is BaseDisputeKit { // ************************************* // // * Structs * // // ************************************* // enum Phase { resolving, // No disputes that need drawing. generating, // Waiting for a random number. Pass as soon as it is ready. drawing // Jurors can be drawn. } struct Dispute { Round[] rounds; // Rounds of the dispute. 0 is the default round, and [1, ..n] are the appeal rounds. uint256 numberOfChoices; // The number of choices jurors have when voting. This does not include choice `0` which is reserved for "refuse to arbitrate". uint256 nbVotes; // Maximal number of votes this dispute can get. } struct Round { Vote[] votes; // Former votes[_appeal][]. uint256 winningChoice; // The choice with the most votes. Note that in the case of a tie, it is the choice that reached the tied number of votes first. mapping(uint256 => uint256) counts; // The sum of votes for each choice in the form `counts[choice]`. bool tied; // True if there is a tie, false otherwise. uint256 totalVoted; // Former uint[_appeal] votesInEachRound. uint256 totalCommitted; // Former commitsInRound. mapping(uint256 => uint256) paidFees; // Tracks the fees paid for each choice in this round. mapping(uint256 => bool) hasPaid; // True if this choice was fully funded, false otherwise. mapping(address => mapping(uint256 => uint256)) contributions; // Maps contributors to their contributions for each choice. uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the ruling that ultimately wins a dispute. uint256[] fundedChoices; // Stores the choices that are fully funded. } struct Vote { address account; // The address of the juror. bytes32 commit; // The commit of the juror. For courts with hidden votes. uint256 choice; // The choice of the juror. bool voted; // True if the vote has been cast. } // ************************************* // // * Storage * // // ************************************* // uint256 public constant WINNER_STAKE_MULTIPLIER = 10000; // Multiplier of the appeal cost that the winner has to pay as fee stake for a round in basis points. Default is 1x of appeal fee. uint256 public constant LOSER_STAKE_MULTIPLIER = 20000; // Multiplier of the appeal cost that the loser has to pay as fee stake for a round in basis points. Default is 2x of appeal fee. uint256 public constant LOSER_APPEAL_PERIOD_MULTIPLIER = 5000; // Multiplier of the appeal period for the choice that wasn't voted for in the previous round, in basis points. Default is 1/2 of original appeal period. uint256 public constant ONE_BASIS_POINT = 10000; // One basis point, for scaling. RNG public rng; // The random number generator IProofOfHumanity public poh; // The Proof of Humanity registry uint256 public RNBlock; // The block number when the random number was requested. uint256 public RN; // The current random number. Phase public phase; // Current phase of this dispute kit. uint256 public disputesWithoutJurors; // The number of disputes that have not finished drawing jurors. Dispute[] public disputes; // Array of the locally created disputes. mapping(uint256 => uint256) public coreDisputeIDToLocal; // Maps the dispute ID in Kleros Core to the local dispute ID. // ************************************* // // * Events * // // ************************************* // event Contribution( uint256 indexed _disputeID, uint256 indexed _round, uint256 _choice, address indexed _contributor, uint256 _amount ); event Withdrawal( uint256 indexed _disputeID, uint256 indexed _round, uint256 _choice, address indexed _contributor, uint256 _amount ); event ChoiceFunded(uint256 indexed _disputeID, uint256 indexed _round, uint256 indexed _choice); event NewPhaseDisputeKit(Phase _phase); /** @dev Constructor. * @param _governor The governor's address. * @param _core The KlerosCore arbitrator. * @param _rng The random number generator. */ constructor( address _governor, KlerosCore _core, RNG _rng, IProofOfHumanity _poh ) BaseDisputeKit(_governor, _core) { rng = _rng; poh = _poh; } // ************************ // // * Governance * // // ************************ // /** @dev Changes the `governor` storage variable. * @param _governor The new value for the `governor` storage variable. */ function changeGovernor(address payable _governor) external onlyByGovernor { governor = _governor; } /** @dev Changes the `core` storage variable. * @param _core The new value for the `core` storage variable. */ function changeCore(address _core) external onlyByGovernor { core = KlerosCore(_core); } /** @dev Changes the `poh` storage variable. * @param _poh The new value for the `poh` storage variable. */ function changePoh(address _poh) external onlyByGovernor { poh = IProofOfHumanity(_poh); } // ************************************* // // * State Modifiers * // // ************************************* // /** @dev Creates a local dispute and maps it to the dispute ID in the Core contract. * Note: Access restricted to Kleros Core only. * @param _disputeID The ID of the dispute in Kleros Core. * @param _numberOfChoices Number of choices of the dispute * @param _extraData Additional info about the dispute, for possible use in future dispute kits. * @param _nbVotes Number of votes. */ function createDispute( uint256 _disputeID, uint256 _numberOfChoices, bytes calldata _extraData, uint256 _nbVotes ) external override onlyByCore { uint256 localDisputeID = disputes.length; Dispute storage dispute = disputes.push(); dispute.numberOfChoices = _numberOfChoices; dispute.nbVotes = _nbVotes; Round storage round = dispute.rounds.push(); round.tied = true; coreDisputeIDToLocal[_disputeID] = localDisputeID; disputesWithoutJurors++; } /** @dev Passes the phase. */ function passPhase() external { require(core.allowSwitchPhase(), "Switching is not allowed"); if (phase == Phase.resolving) { require(disputesWithoutJurors > 0, "There are no disputes that need jurors."); require(block.number >= core.getFreezeBlock() + 20); // TODO: RNG process is currently unfinished. RNBlock = block.number; rng.requestRN(block.number); phase = Phase.generating; } else if (phase == Phase.generating) { RN = rng.getRN(RNBlock); require(RN != 0, "Random number is not ready yet."); phase = Phase.drawing; } else if (phase == Phase.drawing) { // The phase will be switched to 'resolving' by KlerosCore. revert("Already in the last phase"); } emit NewPhaseDisputeKit(phase); } /** @dev Draws the juror from the sortition tree. The drawn address is picked up by Kleros Core. * Note: Access restricted to Kleros Core only. * @param _disputeID The ID of the dispute in Kleros Core. * @return drawnAddress The drawn address. */ function draw(uint256 _disputeID) external override onlyByCore returns (address drawnAddress) { require(phase == Phase.drawing, "Should be in drawing phase"); bytes32 key = bytes32(core.getSubcourtID(_disputeID)); // Get the ID of the tree. uint256 drawnNumber = getRandomNumber(); (uint256 K, , uint256[] memory nodes) = core.getSortitionSumTree(key); uint256 treeIndex = 0; uint256 currentDrawnNumber = drawnNumber % nodes[0]; Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Round storage round = dispute.rounds[dispute.rounds.length - 1]; // TODO: Handle the situation when no one has staked yet. // While it still has children while ((K * treeIndex) + 1 < nodes.length) { for (uint256 i = 1; i <= K; i++) { // Loop over children. uint256 nodeIndex = (K * treeIndex) + i; uint256 nodeValue = nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) { // Go to the next child. currentDrawnNumber -= nodeValue; } else { // Pick this child. treeIndex = nodeIndex; break; } } } bytes32 ID = core.getSortitionSumTreeID(key, treeIndex); drawnAddress = stakePathIDToAccount(ID); if (postDrawCheck(_disputeID, drawnAddress)) { round.votes.push(Vote({account: drawnAddress, commit: bytes32(0), choice: 0, voted: false})); if (round.votes.length == dispute.nbVotes) { disputesWithoutJurors--; } } else { drawnAddress = address(0); } } /** @dev Sets the caller's commit for the specified votes. * `O(n)` where * `n` is the number of votes. * @param _disputeID The ID of the dispute. * @param _voteIDs The IDs of the votes. * @param _commit The commit. */ function castCommit( uint256 _disputeID, uint256[] calldata _voteIDs, bytes32 _commit ) external { require( core.getCurrentPeriod(_disputeID) == KlerosCore.Period.commit, "The dispute should be in Commit period." ); require(_commit != bytes32(0), "Empty commit."); Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Round storage round = dispute.rounds[dispute.rounds.length - 1]; for (uint256 i = 0; i < _voteIDs.length; i++) { require(round.votes[_voteIDs[i]].account == msg.sender, "The caller has to own the vote."); require(round.votes[_voteIDs[i]].commit == bytes32(0), "Already committed this vote."); round.votes[_voteIDs[i]].commit = _commit; } round.totalCommitted += _voteIDs.length; if (round.totalCommitted == round.votes.length) core.passPeriod(_disputeID); } /** @dev Sets the caller's choices for the specified votes. * `O(n)` where * `n` is the number of votes. * @param _disputeID The ID of the dispute. * @param _voteIDs The IDs of the votes. * @param _choice The choice. * @param _salt The salt for the commit if the votes were hidden. */ function castVote( uint256 _disputeID, uint256[] calldata _voteIDs, uint256 _choice, uint256 _salt ) external { require(core.getCurrentPeriod(_disputeID) == KlerosCore.Period.vote, "The dispute should be in Vote period."); require(_voteIDs.length > 0, "No voteID provided"); Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; require(_choice <= dispute.numberOfChoices, "Choice out of bounds"); Round storage round = dispute.rounds[dispute.rounds.length - 1]; bool hiddenVotes = core.areVotesHidden(core.getSubcourtID(_disputeID)); // Save the votes. for (uint256 i = 0; i < _voteIDs.length; i++) { require(round.votes[_voteIDs[i]].account == msg.sender, "The caller has to own the vote."); require( !hiddenVotes || round.votes[_voteIDs[i]].commit == keccak256(abi.encodePacked(_choice, _salt)), "The commit must match the choice in subcourts with hidden votes." ); require(!round.votes[_voteIDs[i]].voted, "Vote already cast."); round.votes[_voteIDs[i]].choice = _choice; round.votes[_voteIDs[i]].voted = true; } round.totalVoted += _voteIDs.length; round.counts[_choice] += _voteIDs.length; if (_choice == round.winningChoice) { if (round.tied) round.tied = false; } else { // Voted for another choice. if (round.counts[_choice] == round.counts[round.winningChoice]) { // Tie. if (!round.tied) round.tied = true; } else if (round.counts[_choice] > round.counts[round.winningChoice]) { // New winner. round.winningChoice = _choice; round.tied = false; } } // Automatically switch period when voting is finished. if (round.totalVoted == round.votes.length) core.passPeriod(_disputeID); } /** @dev Manages contributions, and appeals a dispute if at least two choices are fully funded. * Note that the surplus deposit will be reimbursed. * @param _disputeID Index of the dispute in Kleros Core contract. * @param _choice A choice that receives funding. */ function fundAppeal(uint256 _disputeID, uint256 _choice) external payable { Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; require(_choice <= dispute.numberOfChoices, "There is no such ruling to fund."); (uint256 appealPeriodStart, uint256 appealPeriodEnd) = core.appealPeriod(_disputeID); require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Appeal period is over."); uint256 multiplier; if (this.currentRuling(_disputeID) == _choice) { multiplier = WINNER_STAKE_MULTIPLIER; } else { require( block.timestamp - appealPeriodStart < ((appealPeriodEnd - appealPeriodStart) * LOSER_APPEAL_PERIOD_MULTIPLIER) / ONE_BASIS_POINT, "Appeal period is over for loser" ); multiplier = LOSER_STAKE_MULTIPLIER; } Round storage round = dispute.rounds[dispute.rounds.length - 1]; require(!round.hasPaid[_choice], "Appeal fee is already paid."); uint256 appealCost = core.appealCost(_disputeID); uint256 totalCost = appealCost + (appealCost * multiplier) / ONE_BASIS_POINT; // Take up to the amount necessary to fund the current round at the current costs. uint256 contribution; if (totalCost > round.paidFees[_choice]) { contribution = totalCost - round.paidFees[_choice] > msg.value // Overflows and underflows will be managed on the compiler level. ? msg.value : totalCost - round.paidFees[_choice]; emit Contribution(_disputeID, dispute.rounds.length - 1, _choice, msg.sender, contribution); } round.contributions[msg.sender][_choice] += contribution; round.paidFees[_choice] += contribution; if (round.paidFees[_choice] >= totalCost) { round.feeRewards += round.paidFees[_choice]; round.fundedChoices.push(_choice); round.hasPaid[_choice] = true; emit ChoiceFunded(_disputeID, dispute.rounds.length - 1, _choice); } if (round.fundedChoices.length > 1) { // At least two sides are fully funded. round.feeRewards = round.feeRewards - appealCost; Round storage newRound = dispute.rounds.push(); newRound.tied = true; disputesWithoutJurors++; core.appeal{value: appealCost}(_disputeID); dispute.nbVotes = core.getNumberOfVotes(_disputeID); } if (msg.value > contribution) payable(msg.sender).send(msg.value - contribution); } /** @dev Allows those contributors who attempted to fund an appeal round to withdraw any reimbursable fees or rewards after the dispute gets resolved. * @param _disputeID Index of the dispute in Kleros Core contract. * @param _beneficiary The address whose rewards to withdraw. * @param _round The round the caller wants to withdraw from. * @param _choice The ruling option that the caller wants to withdraw from. * @return amount The withdrawn amount. */ function withdrawFeesAndRewards( uint256 _disputeID, address payable _beneficiary, uint256 _round, uint256 _choice ) external returns (uint256 amount) { require(core.isRuled(_disputeID), "Dispute should be resolved."); Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Round storage round = dispute.rounds[_round]; uint256 finalRuling = this.currentRuling(_disputeID); if (!round.hasPaid[_choice]) { // Allow to reimburse if funding was unsuccessful for this ruling option. amount = round.contributions[_beneficiary][_choice]; } else { // Funding was successful for this ruling option. if (_choice == finalRuling) { // This ruling option is the ultimate winner. amount = round.paidFees[_choice] > 0 ? (round.contributions[_beneficiary][_choice] * round.feeRewards) / round.paidFees[_choice] : 0; } else if (!round.hasPaid[finalRuling]) { // The ultimate winner was not funded in this round. In this case funded ruling option(s) are reimbursed. amount = (round.contributions[_beneficiary][_choice] * round.feeRewards) / (round.paidFees[round.fundedChoices[0]] + round.paidFees[round.fundedChoices[1]]); } } round.contributions[_beneficiary][_choice] = 0; if (amount != 0) { _beneficiary.send(amount); // Deliberate use of send to prevent reverting fallback. It's the user's responsibility to accept ETH. emit Withdrawal(_disputeID, _round, _choice, _beneficiary, amount); } } // ************************************* // // * Public Views * // // ************************************* // /** @dev Gets the current ruling of a specified dispute. * @param _disputeID The ID of the dispute in Kleros Core. * @return ruling The current ruling. */ function currentRuling(uint256 _disputeID) external view override returns (uint256 ruling) { Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Round storage round = dispute.rounds[dispute.rounds.length - 1]; ruling = round.tied ? 0 : round.winningChoice; } /** @dev Gets the degree of coherence of a particular voter. This function is called by Kleros Core in order to determine the amount of the reward. * @param _disputeID The ID of the dispute in Kleros Core. * @param _round The ID of the round. * @param _voteID The ID of the vote. * @return The degree of coherence in basis points. */ function getDegreeOfCoherence( uint256 _disputeID, uint256 _round, uint256 _voteID ) external view override returns (uint256) { // In this contract this degree can be either 0 or 1, but in other dispute kits this value can be something in between. Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Round storage lastRound = dispute.rounds[dispute.rounds.length - 1]; Vote storage vote = dispute.rounds[_round].votes[_voteID]; if (vote.voted && (vote.choice == lastRound.winningChoice || lastRound.tied)) { return ONE_BASIS_POINT; } else { return 0; } } /** @dev Gets the number of jurors who are eligible to a reward in this round. * @param _disputeID The ID of the dispute in Kleros Core. * @param _round The ID of the round. * @return The number of coherent jurors. */ function getCoherentCount(uint256 _disputeID, uint256 _round) external view override returns (uint256) { Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Round storage lastRound = dispute.rounds[dispute.rounds.length - 1]; Round storage currentRound = dispute.rounds[_round]; uint256 winningChoice = lastRound.winningChoice; if (currentRound.totalVoted == 0 || (!lastRound.tied && currentRound.counts[winningChoice] == 0)) { return 0; } else if (lastRound.tied) { return currentRound.totalVoted; } else { return currentRound.counts[winningChoice]; } } /** @dev Returns true if the specified voter was active in this round. * @param _disputeID The ID of the dispute in Kleros Core. * @param _round The ID of the round. * @param _voteID The ID of the voter. * @return Whether the voter was active or not. */ function isVoteActive( uint256 _disputeID, uint256 _round, uint256 _voteID ) external view override returns (bool) { Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Vote storage vote = dispute.rounds[_round].votes[_voteID]; return vote.voted; } function getRoundInfo( uint256 _disputeID, uint256 _round, uint256 _choice ) external view override returns ( uint256 winningChoice, bool tied, uint256 totalVoted, uint256 totalCommited, uint256 nbVoters, uint256 choiceCount ) { Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Round storage round = dispute.rounds[_round]; return ( round.winningChoice, round.tied, round.totalVoted, round.totalCommitted, round.votes.length, round.counts[_choice] ); } function getVoteInfo( uint256 _disputeID, uint256 _round, uint256 _voteID ) external view override returns ( address account, bytes32 commit, uint256 choice, bool voted ) { Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Vote storage vote = dispute.rounds[_round].votes[_voteID]; return (vote.account, vote.commit, vote.choice, vote.voted); } function onCoreFreezingPhase() external onlyByCore { phase = Phase.resolving; emit NewPhaseDisputeKit(phase); } function getDisputesWithoutJurors() external view returns (uint256) { return disputesWithoutJurors; } // ************************************* // // * Internal * // // ************************************* // function postDrawCheck(uint256 _disputeID, address _juror) internal view override returns (bool) { uint256 subcourtID = core.getSubcourtID(_disputeID); (uint256 lockedAmountPerJuror, , , , ) = core.getRoundInfo(_disputeID, core.getNumberOfRounds(_disputeID) - 1); (uint256 stakedTokens, uint256 lockedTokens) = core.getJurorBalance(_juror, uint96(subcourtID)); if (stakedTokens < lockedTokens + lockedAmountPerJuror) { return false; } else { return proofOfHumanity(_juror); } } /** @dev Checks if an address belongs to the Proof of Humanity registry. * @param _address The address to check. * @return registered True if registered. */ function proofOfHumanity(address _address) internal view returns (bool) { return poh.isRegistered(_address); } /** @dev RNG function * @return rn A random number. */ function getRandomNumber() internal returns (uint256) { return rng.getUncorrelatedRN(RNBlock); } /** @dev Retrieves a juror's address from the stake path ID. * @param _stakePathID The stake path ID to unpack. * @return account The account. */ function stakePathIDToAccount(bytes32 _stakePathID) internal pure returns (address account) { assembly { // solium-disable-line security/no-inline-assembly let ptr := mload(0x40) for { let i := 0x00 } lt(i, 0x14) { i := add(i, 0x01) } { mstore8(add(add(ptr, 0x0c), i), byte(i, _stakePathID)) } account := mload(ptr) } } }
Gets the number of jurors who are eligible to a reward in this round. _disputeID The ID of the dispute in Kleros Core. _round The ID of the round. return The number of coherent jurors./
function getCoherentCount(uint256 _disputeID, uint256 _round) external view override returns (uint256) { Dispute storage dispute = disputes[coreDisputeIDToLocal[_disputeID]]; Round storage lastRound = dispute.rounds[dispute.rounds.length - 1]; Round storage currentRound = dispute.rounds[_round]; uint256 winningChoice = lastRound.winningChoice; if (currentRound.totalVoted == 0 || (!lastRound.tied && currentRound.counts[winningChoice] == 0)) { return 0; return currentRound.totalVoted; return currentRound.counts[winningChoice]; } }
7,216,616
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeDecimalMath} from "./SafeDecimalMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {IERC20} from "./interfaces/IERC20.sol"; import "./interfaces/IConjure.sol"; import "./interfaces/IConjureFactory.sol"; import "./interfaces/IConjureRouter.sol"; /// @author Conjure Finance Team /// @title EtherCollateral /// @notice Contract to create a collateral system for conjure /// @dev Fork of https://github.com/Synthetixio/synthetix/blob/develop/contracts/EtherCollateralsUSD.sol and adopted contract EtherCollateral is ReentrancyGuard { using SafeMath for uint256; using SafeDecimalMath for uint256; // ========== CONSTANTS ========== uint256 internal constant ONE_THOUSAND = 1e18 * 1000; uint256 internal constant ONE_HUNDRED = 1e18 * 100; uint256 internal constant ONE_HUNDRED_TEN = 1e18 * 110; // ========== SETTER STATE VARIABLES ========== // The ratio of Collateral to synths issued uint256 public collateralizationRatio; // Minting fee for issuing the synths uint256 public issueFeeRate; // Minimum amount of ETH to create loan preventing griefing and gas consumption. Min 0.05 ETH uint256 public constant MIN_LOAN_COLLATERAL_SIZE = 10 ** 18 / 20; // Maximum number of loans an account can create uint256 public constant ACCOUNT_LOAN_LIMITS = 50; // Liquidation ratio when loans can be liquidated uint256 public liquidationRatio; // Liquidation penalty when loans are liquidated. default 10% uint256 public constant LIQUIDATION_PENALTY = 10 ** 18 / 10; // ========== STATE VARIABLES ========== // The total number of synths issued by the collateral in this contract uint256 public totalIssuedSynths; // Total number of loans ever created uint256 public totalLoansCreated; // Total number of open loans uint256 public totalOpenLoanCount; // Synth loan storage struct struct SynthLoanStruct { // Account that created the loan address payable account; // Amount (in collateral token ) that they deposited uint256 collateralAmount; // Amount (in synths) that they issued to borrow uint256 loanAmount; // Minting Fee uint256 mintingFee; // When the loan was created uint256 timeCreated; // ID for the loan uint256 loanID; // When the loan was paid back (closed) uint256 timeClosed; } // Users Loans by address mapping(address => SynthLoanStruct[]) public accountsSynthLoans; // Account Open Loan Counter mapping(address => uint256) public accountOpenLoanCounter; // address of the conjure contract (which represents the asset) address payable public arbasset; // the address of the collateral contract factory address public _factoryContract; // bool indicating if the asset is closed (no more opening loans and deposits) // this is set to true if the asset price reaches 0 bool internal assetClosed; // address of the owner address public owner; // ========== EVENTS ========== event IssueFeeRateUpdated(uint256 issueFeeRate); event LoanLiquidationOpenUpdated(bool loanLiquidationOpen); event LoanCreated(address indexed account, uint256 loanID, uint256 amount); event LoanClosed(address indexed account, uint256 loanID); event LoanLiquidated(address indexed account, uint256 loanID, address liquidator); event LoanPartiallyLiquidated( address indexed account, uint256 loanID, address liquidator, uint256 liquidatedAmount, uint256 liquidatedCollateral ); event CollateralDeposited(address indexed account, uint256 loanID, uint256 collateralAmount, uint256 collateralAfter); event CollateralWithdrawn(address indexed account, uint256 loanID, uint256 amountWithdrawn, uint256 collateralAfter); event LoanRepaid(address indexed account, uint256 loanID, uint256 repaidAmount, uint256 newLoanAmount); event AssetClosed(bool status); event NewOwner(address newOwner); constructor() { // Don't allow implementation to be initialized. _factoryContract = address(1); } // modifier for only owner modifier onlyOwner { _onlyOwner(); _; } // only owner view for modifier function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } /** * @dev initializes the clone implementation and the EtherCollateral contract * * @param _asset the asset with which the EtherCollateral contract is linked * @param _owner the owner of the asset * @param _factoryAddress the address of the conjure factory for later fee sending * @param _mintingFeeRatio array which holds the minting fee and the c-ratio */ function initialize( address payable _asset, address _owner, address _factoryAddress, uint256[2] memory _mintingFeeRatio ) external { require(_factoryContract == address(0), "already initialized"); require(_factoryAddress != address(0), "factory can not be null"); require(_owner != address(0), "_owner can not be null"); require(_asset != address(0), "_asset can not be null"); // c-ratio greater 100 and less or equal 1000 require(_mintingFeeRatio[1] <= ONE_THOUSAND, "C-Ratio Too high"); require(_mintingFeeRatio[1] > ONE_HUNDRED_TEN, "C-Ratio Too low"); arbasset = _asset; owner = _owner; setIssueFeeRateInternal(_mintingFeeRatio[0]); _factoryContract = _factoryAddress; collateralizationRatio = _mintingFeeRatio[1]; liquidationRatio = _mintingFeeRatio[1] / 100; } // ========== SETTERS ========== /** * @dev lets the owner change the contract owner * * @param _newOwner the new owner address of the contract */ function changeOwner(address payable _newOwner) external onlyOwner { require(_newOwner != address(0), "_newOwner can not be null"); owner = _newOwner; emit NewOwner(_newOwner); } /** * @dev Sets minting fee of the asset internal function * * @param _issueFeeRate the new minting fee */ function setIssueFeeRateInternal(uint256 _issueFeeRate) internal { // max 2.5% fee for minting require(_issueFeeRate <= 250, "Minting fee too high"); issueFeeRate = _issueFeeRate; emit IssueFeeRateUpdated(issueFeeRate); } /** * @dev Sets minting fee of the asset * * @param _issueFeeRate the new minting fee */ function setIssueFeeRate(uint256 _issueFeeRate) external onlyOwner { // fee can only be lowered require(_issueFeeRate <= issueFeeRate, "Fee can only be lowered"); setIssueFeeRateInternal(_issueFeeRate); } /** * @dev Sets the assetClosed indicator if loan opening is allowed or not * Called by the Conjure contract if the asset price reaches 0. * */ function setAssetClosed(bool status) external { require(msg.sender == arbasset, "Only Conjure contract can call"); assetClosed = status; emit AssetClosed(status); } /** * @dev Gets the assetClosed indicator */ function getAssetClosed() external view returns (bool) { return assetClosed; } /** * @dev Gets all the contract information currently in use * array indicating which tokens had their prices updated. * * @return _collateralizationRatio the current C-Ratio * @return _issuanceRatio the percentage of 100/ C-ratio e.g. 100/150 = 0.6666666667 * @return _issueFeeRate the minting fee for a new loan * @return _minLoanCollateralSize the minimum loan collateral value * @return _totalIssuedSynths the total of all issued synths * @return _totalLoansCreated the total of all loans created * @return _totalOpenLoanCount the total of open loans * @return _ethBalance the current balance of the contract */ function getContractInfo() external view returns ( uint256 _collateralizationRatio, uint256 _issuanceRatio, uint256 _issueFeeRate, uint256 _minLoanCollateralSize, uint256 _totalIssuedSynths, uint256 _totalLoansCreated, uint256 _totalOpenLoanCount, uint256 _ethBalance ) { _collateralizationRatio = collateralizationRatio; _issuanceRatio = issuanceRatio(); _issueFeeRate = issueFeeRate; _minLoanCollateralSize = MIN_LOAN_COLLATERAL_SIZE; _totalIssuedSynths = totalIssuedSynths; _totalLoansCreated = totalLoansCreated; _totalOpenLoanCount = totalOpenLoanCount; _ethBalance = address(this).balance; } /** * @dev Gets the value of of 100 / collateralizationRatio. * e.g. 100/150 = 0.6666666667 * */ function issuanceRatio() public view returns (uint256) { // this rounds so you get slightly more rather than slightly less return ONE_HUNDRED.divideDecimalRound(collateralizationRatio); } /** * @dev Gets the amount of synths which can be issued given a certain loan amount * * @param collateralAmount the given ETH amount * @return the amount of synths which can be minted with the given collateral amount */ function loanAmountFromCollateral(uint256 collateralAmount) public view returns (uint256) { return collateralAmount .multiplyDecimal(issuanceRatio()) .multiplyDecimal(syntharb().getLatestETHUSDPrice()) .divideDecimal(syntharb().getLatestPrice()); } /** * @dev Gets the collateral amount needed (in ETH) to mint a given amount of synths * * @param loanAmount the given loan amount * @return the amount of collateral (in ETH) needed to open a loan for the synth amount */ function collateralAmountForLoan(uint256 loanAmount) public view returns (uint256) { return loanAmount .multiplyDecimal(collateralizationRatio .divideDecimalRound(syntharb().getLatestETHUSDPrice()) .multiplyDecimal(syntharb().getLatestPrice())) .divideDecimalRound(ONE_HUNDRED); } /** * @dev Gets the minting fee given the account address and the loanID * * @param _account the opener of the loan * @param _loanID the loan id * @return the minting fee of the loan */ function getMintingFee(address _account, uint256 _loanID) external view returns (uint256) { // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); return synthLoan.mintingFee; } /** * @dev Gets the amount to liquidate which can potentially fix the c ratio given this formula: * r = target issuance ratio * D = debt balance * V = Collateral * P = liquidation penalty * Calculates amount of synths = (D - V * r) / (1 - (1 + P) * r) * * If the C-Ratio is greater than Liquidation Ratio + Penalty in % then the C-Ratio can be fixed * otherwise a greater number is returned and the debtToCover from the calling function is used * * @param debtBalance the amount of the loan or debt to calculate in USD * @param collateral the amount of the collateral in USD * * @return the amount to liquidate to fix the C-Ratio if possible */ function calculateAmountToLiquidate(uint debtBalance, uint collateral) public view returns (uint) { uint unit = SafeDecimalMath.unit(); uint dividend = debtBalance.sub(collateral.divideDecimal(liquidationRatio)); uint divisor = unit.sub(unit.add(LIQUIDATION_PENALTY).divideDecimal(liquidationRatio)); return dividend.divideDecimal(divisor); } /** * @dev Gets all open loans by a given account address * * @param _account the opener of the loans * @return all open loans by ID in form of an array */ function getOpenLoanIDsByAccount(address _account) external view returns (uint256[] memory) { SynthLoanStruct[] memory synthLoans = accountsSynthLoans[_account]; uint256[] memory _openLoanIDs = new uint256[](synthLoans.length); uint256 j; for (uint i = 0; i < synthLoans.length; i++) { if (synthLoans[i].timeClosed == 0) { _openLoanIDs[j++] = synthLoans[i].loanID; } } // Change the list size of the array in place assembly { mstore(_openLoanIDs, j) } // Return the resized array return _openLoanIDs; } /** * @dev Gets all details about a certain loan * * @param _account the opener of the loans * @param _loanID the ID of a given loan * @return account the opener of the loan * @return collateralAmount the amount of collateral in ETH * @return loanAmount the loan amount * @return timeCreated the time the loan was initially created * @return loanID the ID of the loan * @return timeClosed the closure time of the loan (if closed) * @return totalFees the minting fee of the loan */ function getLoan(address _account, uint256 _loanID) external view returns ( address account, uint256 collateralAmount, uint256 loanAmount, uint256 timeCreated, uint256 loanID, uint256 timeClosed, uint256 totalFees ) { SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); account = synthLoan.account; collateralAmount = synthLoan.collateralAmount; loanAmount = synthLoan.loanAmount; timeCreated = synthLoan.timeCreated; loanID = synthLoan.loanID; timeClosed = synthLoan.timeClosed; totalFees = synthLoan.mintingFee; } /** * @dev Gets the current C-Ratio of a loan * * @param _account the opener of the loan * @param _loanID the loan ID * @return loanCollateralRatio the current C-Ratio of the loan */ function getLoanCollateralRatio(address _account, uint256 _loanID) external view returns (uint256 loanCollateralRatio) { // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID); (loanCollateralRatio, ) = _loanCollateralRatio(synthLoan); } /** * @dev Gets the current C-Ratio of a loan by _loan struct * * @param _loan the loan struct * @return loanCollateralRatio the current C-Ratio of the loan * @return collateralValue the current value of the collateral in USD */ function _loanCollateralRatio(SynthLoanStruct memory _loan) internal view returns ( uint256 loanCollateralRatio, uint256 collateralValue ) { uint256 loanAmountWithAccruedInterest = _loan.loanAmount.multiplyDecimal(syntharb().getLatestPrice()); collateralValue = _loan.collateralAmount.multiplyDecimal(syntharb().getLatestETHUSDPrice()); loanCollateralRatio = collateralValue.divideDecimal(loanAmountWithAccruedInterest); } // ========== PUBLIC FUNCTIONS ========== /** * @dev Public function to open a new loan in the system * * @param _loanAmount the amount of synths a user wants to take a loan for * @return loanID the ID of the newly created loan */ function openLoan(uint256 _loanAmount) external payable nonReentrant returns (uint256 loanID) { // asset must be open require(!assetClosed, "Asset closed"); // Require ETH sent to be greater than MIN_LOAN_COLLATERAL_SIZE require( msg.value >= MIN_LOAN_COLLATERAL_SIZE, "Not enough ETH to create this loan. Please see the MIN_LOAN_COLLATERAL_SIZE" ); // Each account is limited to creating 50 (ACCOUNT_LOAN_LIMITS) loans require(accountsSynthLoans[msg.sender].length < ACCOUNT_LOAN_LIMITS, "Each account is limited to 50 loans"); // Calculate issuance amount based on issuance ratio syntharb().updatePrice(); uint256 maxLoanAmount = loanAmountFromCollateral(msg.value); // Require requested _loanAmount to be less than maxLoanAmount // Issuance ratio caps collateral to loan value at 120% require(_loanAmount <= maxLoanAmount, "Loan amount exceeds max borrowing power"); uint256 ethForLoan = collateralAmountForLoan(_loanAmount); uint256 mintingFee = _calculateMintingFee(msg.value); require(msg.value >= ethForLoan + mintingFee, "Not enough funds sent to cover fee and collateral"); // Get a Loan ID loanID = _incrementTotalLoansCounter(); // Create Loan storage object SynthLoanStruct memory synthLoan = SynthLoanStruct({ account: msg.sender, collateralAmount: msg.value - mintingFee, loanAmount: _loanAmount, mintingFee: mintingFee, timeCreated: block.timestamp, loanID: loanID, timeClosed: 0 }); // Record loan in mapping to account in an array of the accounts open loans accountsSynthLoans[msg.sender].push(synthLoan); // Increment totalIssuedSynths totalIssuedSynths = totalIssuedSynths.add(_loanAmount); // Issue the synth (less fee) syntharb().mint(msg.sender, _loanAmount); // Tell the Dapps a loan was created emit LoanCreated(msg.sender, loanID, _loanAmount); // Fee distribution. Mint the fees into the FeePool and record fees paid if (mintingFee > 0) { // conjureRouter gets 25% of the fee address payable conjureRouter = IConjureFactory(_factoryContract).getConjureRouter(); uint256 feeToSend = mintingFee / 4; IConjureRouter(conjureRouter).deposit{value:feeToSend}(); arbasset.transfer(mintingFee.sub(feeToSend)); } } /** * @dev Function to close a loan * calls the internal _closeLoan function with the false parameter for liquidation * to mark it as a non liquidation close * * @param loanID the ID of the loan a user wants to close */ function closeLoan(uint256 loanID) external nonReentrant { _closeLoan(msg.sender, loanID, false); } /** * @dev Add ETH collateral to an open loan * * @param account the opener of the loan * @param loanID the ID of the loan */ function depositCollateral(address account, uint256 loanID) external payable { require(msg.value > 0, "Deposit amount must be greater than 0"); // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); uint256 totalCollateral = synthLoan.collateralAmount.add(msg.value); _updateLoanCollateral(synthLoan, totalCollateral); // Tell the Dapps collateral was added to loan emit CollateralDeposited(account, loanID, msg.value, totalCollateral); } /** * @dev Withdraw ETH collateral from an open loan * the C-Ratio after should not be less than the Liquidation Ratio * * @param loanID the ID of the loan * @param withdrawAmount the amount to withdraw from the current collateral */ function withdrawCollateral(uint256 loanID, uint256 withdrawAmount) external nonReentrant { require(withdrawAmount > 0, "Amount to withdraw must be greater than 0"); // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(msg.sender, loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); uint256 collateralAfter = synthLoan.collateralAmount.sub(withdrawAmount); SynthLoanStruct memory loanAfter = _updateLoanCollateral(synthLoan, collateralAfter); // require collateral ratio after to be above the liquidation ratio (uint256 collateralRatioAfter, ) = _loanCollateralRatio(loanAfter); require(collateralRatioAfter > liquidationRatio, "Collateral ratio below liquidation after withdraw"); // Tell the Dapps collateral was added to loan emit CollateralWithdrawn(msg.sender, loanID, withdrawAmount, loanAfter.collateralAmount); // transfer ETH to msg.sender msg.sender.transfer(withdrawAmount); } /** * @dev Repay synths to fix C-Ratio * * @param _loanCreatorsAddress the address of the loan creator * @param _loanID the ID of the loan * @param _repayAmount the amount of synths to be repaid */ function repayLoan( address _loanCreatorsAddress, uint256 _loanID, uint256 _repayAmount ) external { // check msg.sender has sufficient funds to pay require(IERC20(address(syntharb())).balanceOf(msg.sender) >= _repayAmount, "Not enough balance"); SynthLoanStruct memory synthLoan = _getLoanFromStorage(_loanCreatorsAddress, _loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); uint256 loanAmountAfter = synthLoan.loanAmount.sub(_repayAmount); // burn funds from msg.sender for repaid amount syntharb().burn(msg.sender, _repayAmount); // decrease issued synths totalIssuedSynths = totalIssuedSynths.sub(_repayAmount); // update loan with new total loan amount, record accrued interests _updateLoan(synthLoan, loanAmountAfter); emit LoanRepaid(_loanCreatorsAddress, _loanID, _repayAmount, loanAmountAfter); } /** * @dev Liquidate loans at or below issuance ratio * if the liquidation amount is greater or equal to the owed amount it will also trigger a closure of the loan * * @param _loanCreatorsAddress the address of the loan creator * @param _loanID the ID of the loan * @param _debtToCover the amount of synths the liquidator wants to cover */ function liquidateLoan( address _loanCreatorsAddress, uint256 _loanID, uint256 _debtToCover ) external nonReentrant { // check msg.sender (liquidator's wallet) has sufficient require(IERC20(address(syntharb())).balanceOf(msg.sender) >= _debtToCover, "Not enough balance"); SynthLoanStruct memory synthLoan = _getLoanFromStorage(_loanCreatorsAddress, _loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); (uint256 collateralRatio, uint256 collateralValue) = _loanCollateralRatio(synthLoan); // get prices syntharb().updatePrice(); uint currentPrice = syntharb().getLatestPrice(); uint currentEthUsdPrice = syntharb().getLatestETHUSDPrice(); require(collateralRatio < liquidationRatio, "Collateral ratio above liquidation ratio"); // calculate amount to liquidate to fix ratio including accrued interest // multiply the loan amount times current price in usd // collateralValue is already in usd nomination uint256 liquidationAmountUSD = calculateAmountToLiquidate( synthLoan.loanAmount.multiplyDecimal(currentPrice), collateralValue ); // calculate back the synth amount from the usd nomination uint256 liquidationAmount = liquidationAmountUSD.divideDecimal(currentPrice); // cap debt to liquidate uint256 amountToLiquidate = liquidationAmount < _debtToCover ? liquidationAmount : _debtToCover; // burn funds from msg.sender for amount to liquidate syntharb().burn(msg.sender, amountToLiquidate); // decrease issued totalIssuedSynths totalIssuedSynths = totalIssuedSynths.sub(amountToLiquidate); // Collateral value to redeem in ETH uint256 collateralRedeemed = amountToLiquidate.multiplyDecimal(currentPrice).divideDecimal(currentEthUsdPrice); // Add penalty in ETH uint256 totalCollateralLiquidated = collateralRedeemed.multiplyDecimal( SafeDecimalMath.unit().add(LIQUIDATION_PENALTY) ); // update remaining loanAmount less amount paid and update accrued interests less interest paid _updateLoan(synthLoan, synthLoan.loanAmount.sub(amountToLiquidate)); // indicates if we need a full closure bool close; if (synthLoan.collateralAmount <= totalCollateralLiquidated) { close = true; // update remaining collateral on loan _updateLoanCollateral(synthLoan, 0); totalCollateralLiquidated = synthLoan.collateralAmount; } else { // update remaining collateral on loan _updateLoanCollateral(synthLoan, synthLoan.collateralAmount.sub(totalCollateralLiquidated)); } // check if we have a full closure here if (close) { // emit loan liquidation event emit LoanLiquidated( _loanCreatorsAddress, _loanID, msg.sender ); _closeLoan(synthLoan.account, synthLoan.loanID, true); } else { // emit loan liquidation event emit LoanPartiallyLiquidated( _loanCreatorsAddress, _loanID, msg.sender, amountToLiquidate, totalCollateralLiquidated ); } // Send liquidated ETH collateral to msg.sender msg.sender.transfer(totalCollateralLiquidated); } // ========== PRIVATE FUNCTIONS ========== /** * @dev Internal function to close open loans * * @param account the account which opened the loan * @param loanID the ID of the loan to close * @param liquidation bool representing if its a user close or a liquidation close */ function _closeLoan( address account, uint256 loanID, bool liquidation ) private { // Get the loan from storage SynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID); // Check loan exists and is open _checkLoanIsOpen(synthLoan); // Record loan as closed _recordLoanClosure(synthLoan); if (!liquidation) { uint256 repayAmount = synthLoan.loanAmount; require( IERC20(address(syntharb())).balanceOf(msg.sender) >= repayAmount, "You do not have the required Synth balance to close this loan." ); // Decrement totalIssuedSynths totalIssuedSynths = totalIssuedSynths.sub(synthLoan.loanAmount); // Burn all Synths issued for the loan + the fees syntharb().burn(msg.sender, repayAmount); } uint256 remainingCollateral = synthLoan.collateralAmount; // Tell the Dapps emit LoanClosed(account, loanID); // Send remaining collateral to loan creator synthLoan.account.transfer(remainingCollateral); } /** * @dev gets a loan struct from the storage * * @param account the account which opened the loan * @param loanID the ID of the loan to close * @return synthLoan the loan struct given the input parameters */ function _getLoanFromStorage(address account, uint256 loanID) private view returns (SynthLoanStruct memory synthLoan) { SynthLoanStruct[] storage synthLoans = accountsSynthLoans[account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == loanID) { synthLoan = synthLoans[i]; break; } } } /** * @dev updates the loan amount of a loan * * @param _synthLoan the synth loan struct representing the loan * @param _newLoanAmount the new loan amount to update the loan */ function _updateLoan( SynthLoanStruct memory _synthLoan, uint256 _newLoanAmount ) private { // Get storage pointer to the accounts array of loans SynthLoanStruct[] storage synthLoans = accountsSynthLoans[_synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == _synthLoan.loanID) { synthLoans[i].loanAmount = _newLoanAmount; } } } /** * @dev updates the collateral amount of a loan * * @param _synthLoan the synth loan struct representing the loan * @param _newCollateralAmount the new collateral amount to update the loan * @return synthLoan the loan struct given the input parameters */ function _updateLoanCollateral(SynthLoanStruct memory _synthLoan, uint256 _newCollateralAmount) private returns (SynthLoanStruct memory synthLoan) { // Get storage pointer to the accounts array of loans SynthLoanStruct[] storage synthLoans = accountsSynthLoans[_synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == _synthLoan.loanID) { synthLoans[i].collateralAmount = _newCollateralAmount; synthLoan = synthLoans[i]; } } } /** * @dev records the closure of a loan * * @param synthLoan the synth loan struct representing the loan */ function _recordLoanClosure(SynthLoanStruct memory synthLoan) private { // Get storage pointer to the accounts array of loans SynthLoanStruct[] storage synthLoans = accountsSynthLoans[synthLoan.account]; for (uint256 i = 0; i < synthLoans.length; i++) { if (synthLoans[i].loanID == synthLoan.loanID) { // Record the time the loan was closed synthLoans[i].timeClosed = block.timestamp; } } // Reduce Total Open Loans Count totalOpenLoanCount = totalOpenLoanCount.sub(1); } /** * @dev Increments all global counters after a loan creation * * @return the amount of total loans created */ function _incrementTotalLoansCounter() private returns (uint256) { // Increase the total Open loan count totalOpenLoanCount = totalOpenLoanCount.add(1); // Increase the total Loans Created count totalLoansCreated = totalLoansCreated.add(1); // Return total count to be used as a unique ID. return totalLoansCreated; } /** * @dev calculates the minting fee given the 100+ x% of eth collateral and returns x * e.g. input 1.02 ETH fee is set to 2% returns 0.02 ETH as the minting fee * * @param _ethAmount the amount of eth of the collateral * @param mintingFee the fee which is being distributed to the creator and the factory */ function _calculateMintingFee(uint256 _ethAmount) private view returns (uint256 mintingFee) { if (issueFeeRate == 0) { mintingFee = 0; } else { mintingFee = _ethAmount.divideDecimalRound(10000 + issueFeeRate).multiplyDecimal(issueFeeRate); } } /** * @dev checks if a loan is pen in the system * * @param _synthLoan the synth loan struct representing the loan */ function _checkLoanIsOpen(SynthLoanStruct memory _synthLoan) internal pure { require(_synthLoan.loanID > 0, "Loan does not exist"); require(_synthLoan.timeClosed == 0, "Loan already closed"); } /* ========== INTERNAL VIEWS ========== */ /** * @dev Gets the interface of the synthetic asset */ function syntharb() internal view returns (IConjure) { return IConjure(arbasset); } }
Sets minting fee of the asset _issueFeeRate the new minting fee/ fee can only be lowered
function setIssueFeeRate(uint256 _issueFeeRate) external onlyOwner { require(_issueFeeRate <= issueFeeRate, "Fee can only be lowered"); setIssueFeeRateInternal(_issueFeeRate); }
12,915,157
./full_match/43113/0x8139C91ABc630e5C237c1b5e053b7DaaE176cc6f/sources/contracts/stake/AaveIncentivesController_flat.sol
Returns the addition of two unsigned integers, reverting on overflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow./
function getRevision() internal pure virtual returns (uint256); uint256[50] private ______gap; } } } } } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; }
7,209,783
./partial_match/4/0xd81082177050e4c165A015b5992e087A3b703258/sources/CrowDEMO.sol
Give the order amount back to the buyer Remove order amount from total Escrow balance
function complainDelivery(uint256 _orderId) external { require(users[msg.sender].active, "You are not yet Registered"); require( allOrders[_orderId].buyer == msg.sender, "You can't complain someone else order" ); require( allOrders[_orderId].orderStatus == OrderState.AWAITING_DELIVERY, "Cannot complain delivery" ); address buyer = allOrders[_orderId].buyer; uint256 orderAmount = allOrders[_orderId].amount; balances[buyer] += orderAmount; escrowTotalAmount -= orderAmount; }
8,609,845
./partial_match/1/0x4593D5114834071512Ce836E62d03a1AEb71337E/sources/SpaceX.sol
Set maximum transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { require( maxTxAmount >= ((totalSupply() * 1) / 100), "Cannot set maxTransactionAmount lower than 1%" ); _maxTxAmount = maxTxAmount; }
2,637,256
./full_match/4/0xCeE1b0034116B2ca9dE1620D847f66B66f13d6aC/sources/browser/ERC721AuctionV3.sol
拍卖结束 获得自己的资金或NFTreturnMoney[msg.sender] = 0;require(_token.transfer(msg.sender, SafeMath.mul(returnMoney[msg.sender],1018)),"user gather Fail");
function auctionEnd() public payable locked { require(block.timestamp > auctionEndTime,"it's not time yet" ); address winner = getWinner(); if(winner == 0x0000000000000000000000000000000000000000){ erc721.transferFrom(address(this),beneficiary,NFTTokenId); } if(msg.sender == winner){ erc721.transferFrom(address(this),winner,NFTTokenId); } if(msg.sender == beneficiary){ uint256 reward = returnMoney[msg.sender] + hightPrice; beneficiary.transfer(reward); hightPrice = 0; msg.sender.transfer(returnMoney[msg.sender]); } delete returnMoney[msg.sender]; emit AuctionEnded(msg.sender, returnMoney[msg.sender]); }
793,937
// SPDX-License-Identifier: WTFPL pragma solidity >=0.8.4; import "./IOwnable.sol"; /// @notice Emitted when the caller is not the owner. error Ownable__NotOwner(address owner, address caller); /// @notice Emitted when setting the owner to the zero address. error Ownable__OwnerZeroAddress(); /// @title Ownable /// @author Paul Razvan Berg Template addition @Taariq Matthysen contract Ownable is IOwnable { /// PUBLIC STORAGE /// /// @inheritdoc IOwnable address public override owner; /// MODIFIERS /// /// @notice Throws if called by any account other than the owner. modifier onlyOwner() { if (owner != msg.sender) { revert Ownable__NotOwner(owner, msg.sender); } _; } /// CONSTRUCTOR /// /// @notice Initializes the contract setting the deployer as the initial owner. constructor() { address msgSender = msg.sender; owner = msgSender; emit TransferOwnership(address(0), msgSender); } /// PUBLIC NON-CONSTANT FUNCTIONS /// /// @inheritdoc IOwnable function _renounceOwnership() external virtual override onlyOwner { emit TransferOwnership(owner, address(0)); owner = address(0); } /// @inheritdoc IOwnable function _transferOwnership(address newOwner) external virtual override onlyOwner { if (newOwner == address(0)) { revert Ownable__OwnerZeroAddress(); } emit TransferOwnership(owner, newOwner); owner = newOwner; } }
@inheritdoc IOwnable
function _transferOwnership(address newOwner) external virtual override onlyOwner { if (newOwner == address(0)) { revert Ownable__OwnerZeroAddress(); } emit TransferOwnership(owner, newOwner); owner = newOwner; }
7,219,396
// SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "../openzeppelin/access/AccessControl.sol"; import "../openzeppelin/utils/math/SafeMath.sol"; import "../openzeppelin/token/ERC20/SafeERC20.sol"; import "../openzeppelin/token/ERC20/IERC20.sol"; import "../sablierhq/Sablier.sol"; import "./ITokenVesting.sol"; /** * @title TokenVesting contract for linearly vesting tokens to the respective vesting beneficiary * @dev This contract receives accepted proposals from the Manager contract, and pass it to sablier contract * @dev all the tokens to be vested by the vesting beneficiary. It releases these tokens when called * @dev upon in a continuous-like linear fashion. * @notice This contract use https://github.com/sablierhq/sablier-smooth-contracts/blob/master/contracts/Sablier.sol */ contract TokenVesting is ITokenVesting, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; address sablier; uint256 constant CREATOR_IX = 0; uint256 constant ROLL_IX = 1; uint256 constant REFERRAL_IX = 2; uint256 public constant DAYS_IN_SECONDS = 24 * 60 * 60; mapping(address => VestingInfo) public vestingInfo; mapping(address => mapping(uint256 => Beneficiary)) public beneficiaries; mapping(address => address[]) public beneficiaryTokens; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Ownable: caller is not the owner" ); _; } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); grantRole(DEFAULT_ADMIN_ROLE, newOwner); revokeRole(DEFAULT_ADMIN_ROLE, msg.sender); } constructor(address newOwner) { _setupRole(DEFAULT_ADMIN_ROLE, newOwner); } function setSablier(address _sablier) external onlyOwner { sablier = _sablier; } /** * @dev Method to add a token into TokenVesting * @param _token address Address of token * @param _beneficiaries address[3] memory Address of vesting beneficiary * @param _proportions uint256[3] memory Proportions of vesting beneficiary * @param _vestingPeriodInDays uint256 Period of vesting, in units of Days, to be converted * @notice This emits an Event LogTokenAdded which is indexed by the token address */ function addToken( address _token, address[3] calldata _beneficiaries, uint256[3] calldata _proportions, uint256 _vestingPeriodInDays ) external override onlyOwner { uint256 duration = uint256(_vestingPeriodInDays).mul(DAYS_IN_SECONDS); require(duration > 0, "VESTING: period can't be zero"); uint256 stopTime = block.timestamp.add(duration); uint256 initial = IERC20(_token).balanceOf(address(this)); vestingInfo[_token] = VestingInfo({ vestingBeneficiary: _beneficiaries[0], totalBalance: initial, beneficiariesCount: 3, // this is to create a struct compatible with any number but for now is always 3 start: block.timestamp, stop: stopTime }); IERC20(_token).approve(sablier, 2**256 - 1); IERC20(_token).approve(address(this), 2**256 - 1); for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) { if (_beneficiaries[i] == address(0)) { continue; } beneficiaries[_token][i].beneficiary = _beneficiaries[i]; beneficiaries[_token][i].proportion = _proportions[i]; uint256 deposit = _proportions[i]; if (deposit == 0) { continue; } // we store the remaing to guarantee deposit be multiple of period. We send that remining at the end of period. uint256 remaining = deposit % duration; uint256 streamId = Sablier(sablier).createStream( _beneficiaries[i], deposit.sub(remaining), _token, block.timestamp, stopTime ); beneficiaries[_token][i].streamId = streamId; beneficiaries[_token][i].remaining = remaining; beneficiaryTokens[_beneficiaries[i]].push(_token); } emit LogTokenAdded(_token, _beneficiaries[0], _vestingPeriodInDays); } function getBeneficiaryId(address _token, address _beneficiary) internal view returns (uint256) { for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) { if (beneficiaries[_token][i].beneficiary == _beneficiary) { return i; } } revert("VESTING: invalid vesting address"); } function release(address _token, address _beneficiary) external override { uint256 ix = getBeneficiaryId(_token, _beneficiary); uint256 streamId = beneficiaries[_token][ix].streamId; if (!Sablier(sablier).isEntity(streamId)) { return; } uint256 balance = Sablier(sablier).balanceOf(streamId, _beneficiary); bool withdrawResult = Sablier(sablier).withdrawFromStream(streamId, balance); require(withdrawResult, "VESTING: Error calling withdrawFromStream"); // if vesting duration already finish then release the final dust if ( vestingInfo[_token].stop < block.timestamp && beneficiaries[_token][ix].remaining > 0 ) { IERC20(_token).safeTransferFrom( address(this), _beneficiary, beneficiaries[_token][ix].remaining ); } } function releaseableAmount(address _token) public view override returns (uint256) { uint256 total = 0; for (uint256 i = 0; i < vestingInfo[_token].beneficiariesCount; i++) { if (Sablier(sablier).isEntity(beneficiaries[_token][i].streamId)) { total = total + Sablier(sablier).balanceOf( beneficiaries[_token][i].streamId, beneficiaries[_token][i].beneficiary ); } } return total; } function releaseableAmountByAddress(address _token, address _beneficiary) public view override returns (uint256) { uint256 ix = getBeneficiaryId(_token, _beneficiary); uint256 streamId = beneficiaries[_token][ix].streamId; return Sablier(sablier).balanceOf(streamId, _beneficiary); } function vestedAmount(address _token) public view override returns (uint256) { VestingInfo memory info = vestingInfo[_token]; if (block.timestamp >= info.stop) { return info.totalBalance; } else { uint256 duration = info.stop.sub(info.start); return info.totalBalance.mul(block.timestamp.sub(info.start)).div( duration ); } } function getVestingInfo(address _token) external view override returns (VestingInfo memory) { return vestingInfo[_token]; } function updateVestingAddress( address _token, uint256 ix, address _vestingBeneficiary ) internal { if ( vestingInfo[_token].vestingBeneficiary == beneficiaries[_token][ix].beneficiary ) { vestingInfo[_token].vestingBeneficiary = _vestingBeneficiary; } beneficiaries[_token][ix].beneficiary = _vestingBeneficiary; uint256 deposit = 0; uint256 remaining = 0; { uint256 streamId = beneficiaries[_token][ix].streamId; // if there's no pending this will revert and it's ok because has no sense to update the address uint256 pending = Sablier(sablier).balanceOf(streamId, address(this)); uint256 duration = vestingInfo[_token].stop.sub(block.timestamp); deposit = pending.add(beneficiaries[_token][ix].remaining); remaining = deposit % duration; bool cancelResult = Sablier(sablier).cancelStream( beneficiaries[_token][ix].streamId ); require(cancelResult, "VESTING: Error calling cancelStream"); } uint256 streamId = Sablier(sablier).createStream( _vestingBeneficiary, deposit.sub(remaining), _token, block.timestamp, vestingInfo[_token].stop ); beneficiaries[_token][ix].streamId = streamId; beneficiaries[_token][ix].remaining = remaining; emit LogBeneficiaryUpdated(_token, _vestingBeneficiary); } function setVestingAddress( address _vestingBeneficiary, address _token, address _newVestingBeneficiary ) external override onlyOwner { uint256 ix = getBeneficiaryId(_token, _vestingBeneficiary); updateVestingAddress(_token, ix, _newVestingBeneficiary); } function setVestingReferral( address _vestingBeneficiary, address _token, address _vestingReferral ) external override onlyOwner { require( _vestingBeneficiary == vestingInfo[_token].vestingBeneficiary, "VESTING: Only creator" ); updateVestingAddress(_token, REFERRAL_IX, _vestingReferral); } function getAllTokensByBeneficiary(address _beneficiary) public view override returns (address[] memory) { return beneficiaryTokens[_beneficiary]; } function releaseAll(address _beneficiary) public override { address[] memory array = beneficiaryTokens[_beneficiary]; for (uint256 i = 0; i < array.length; i++) { this.release(array[i], _beneficiary); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.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.6.0 <0.8.0; import "./IERC20.sol"; import "../../utils/math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity =0.7.6; import "../openzeppelin/utils/Pausable.sol"; import "../openzeppelin/access/Ownable.sol"; import "../openzeppelin/token/ERC20/IERC20.sol"; import "../openzeppelin/utils/ReentrancyGuard.sol"; import "./compound/Exponential.sol"; import "./interfaces/IERC1620.sol"; import "./Types.sol"; /** * @title Sablier's Money Streaming * @author Sablier */ contract Sablier is IERC1620, Exponential, ReentrancyGuard { /*** Storage Properties ***/ /** * @dev The amount of interest has been accrued per token address. */ mapping(address => uint256) private earnings; /** * @notice The percentage fee charged by the contract on the accrued interest. */ Exp public fee; /** * @notice Counter for new stream ids. */ uint256 public nextStreamId; /** * @dev The stream objects identifiable by their unsigned integer ids. */ mapping(uint256 => Types.Stream) private streams; /*** Modifiers ***/ /** * @dev Throws if the caller is not the sender of the recipient of the stream. */ modifier onlySenderOrRecipient(uint256 streamId) { require( msg.sender == streams[streamId].sender || msg.sender == streams[streamId].recipient, "caller is not the sender or the recipient of the stream" ); _; } /** * @dev Throws if the provided id does not point to a valid stream. */ modifier streamExists(uint256 streamId) { require(streams[streamId].isEntity, "stream does not exist"); _; } /*** Contract Logic Starts Here */ constructor() public { nextStreamId = 1; } /*** View Functions ***/ function isEntity(uint256 streamId) external view returns (bool) { return streams[streamId].isEntity; } /** * @dev Returns the compounding stream with all its properties. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream to query. * @dev The stream object. */ function getStream(uint256 streamId) external view override streamExists(streamId) returns ( address sender, address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 ratePerSecond ) { sender = streams[streamId].sender; recipient = streams[streamId].recipient; deposit = streams[streamId].deposit; tokenAddress = streams[streamId].tokenAddress; startTime = streams[streamId].startTime; stopTime = streams[streamId].stopTime; remainingBalance = streams[streamId].remainingBalance; ratePerSecond = streams[streamId].ratePerSecond; } /** * @dev Returns either the delta in seconds between `block.timestamp` and `startTime` or * between `stopTime` and `startTime, whichever is smaller. If `block.timestamp` is before * `startTime`, it returns 0. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream for which to query the delta. * @dev The time delta in seconds. */ function deltaOf(uint256 streamId) public view streamExists(streamId) returns (uint256 delta) { Types.Stream memory stream = streams[streamId]; if (block.timestamp <= stream.startTime) return 0; if (block.timestamp < stream.stopTime) return block.timestamp - stream.startTime; return stream.stopTime - stream.startTime; } struct BalanceOfLocalVars { MathError mathErr; uint256 recipientBalance; uint256 withdrawalAmount; uint256 senderBalance; } /** * @dev Returns the available funds for the given stream id and address. * @dev Throws if the id does not point to a valid stream. * @param streamId The id of the stream for which to query the balance. * @param who The address for which to query the balance. * @dev @balance uint256 The total funds allocated to `who` as uint256. */ function balanceOf(uint256 streamId, address who) public view override streamExists(streamId) returns (uint256 balance) { Types.Stream memory stream = streams[streamId]; BalanceOfLocalVars memory vars; uint256 delta = deltaOf(streamId); (vars.mathErr, vars.recipientBalance) = mulUInt( delta, stream.ratePerSecond ); require( vars.mathErr == MathError.NO_ERROR, "recipient balance calculation error" ); /* * If the stream `balance` does not equal `deposit`, it means there have been withdrawals. * We have to subtract the total amount withdrawn from the amount of money that has been * streamed until now. */ if (stream.deposit > stream.remainingBalance) { (vars.mathErr, vars.withdrawalAmount) = subUInt( stream.deposit, stream.remainingBalance ); assert(vars.mathErr == MathError.NO_ERROR); (vars.mathErr, vars.recipientBalance) = subUInt( vars.recipientBalance, vars.withdrawalAmount ); /* `withdrawalAmount` cannot and should not be bigger than `recipientBalance`. */ assert(vars.mathErr == MathError.NO_ERROR); } if (who == stream.recipient) return vars.recipientBalance; if (who == stream.sender) { (vars.mathErr, vars.senderBalance) = subUInt( stream.remainingBalance, vars.recipientBalance ); /* `recipientBalance` cannot and should not be bigger than `remainingBalance`. */ assert(vars.mathErr == MathError.NO_ERROR); return vars.senderBalance; } return 0; } /*** Public Effects & Interactions Functions ***/ struct CreateStreamLocalVars { MathError mathErr; uint256 duration; uint256 ratePerSecond; } /** * @notice Creates a new stream funded by `msg.sender` and paid towards `recipient`. * @dev Throws if paused. * Throws if the recipient is the zero address, the contract itself or the caller. * Throws if the deposit is 0. * Throws if the start time is before `block.timestamp`. * Throws if the stop time is before the start time. * Throws if the duration calculation has a math error. * Throws if the deposit is smaller than the duration. * Throws if the deposit is not a multiple of the duration. * Throws if the rate calculation has a math error. * Throws if the next stream id calculation has a math error. * Throws if the contract is not allowed to transfer enough tokens. * Throws if there is a token transfer failure. * @param recipient The address towards which the money is streamed. * @param deposit The amount of money to be streamed. * @param tokenAddress The ERC20 token to use as streaming currency. * @param startTime The unix timestamp for when the stream starts. * @param stopTime The unix timestamp for when the stream stops. * @return The uint256 id of the newly created stream. */ function createStream( address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ) public override returns (uint256) { require(recipient != address(0x00), "stream to the zero address"); require(recipient != address(this), "stream to the contract itself"); require(recipient != msg.sender, "stream to the caller"); require(deposit > 0, "deposit is zero"); require( startTime >= block.timestamp, "start time before block.timestamp" ); require(stopTime > startTime, "stop time before the start time"); CreateStreamLocalVars memory vars; (vars.mathErr, vars.duration) = subUInt(stopTime, startTime); /* `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know `stopTime` is higher than `startTime`. */ assert(vars.mathErr == MathError.NO_ERROR); /* Without this, the rate per second would be zero. */ require(deposit >= vars.duration, "deposit smaller than time delta"); require( deposit % vars.duration == 0, "deposit not multiple of time delta" ); (vars.mathErr, vars.ratePerSecond) = divUInt(deposit, vars.duration); /* `divUInt` can only return MathError.DIVISION_BY_ZERO but we know `duration` is not zero. */ assert(vars.mathErr == MathError.NO_ERROR); /* Create and store the stream object. */ uint256 streamId = nextStreamId; streams[streamId] = Types.Stream({ remainingBalance: deposit, deposit: deposit, isEntity: true, ratePerSecond: vars.ratePerSecond, recipient: recipient, sender: msg.sender, startTime: startTime, stopTime: stopTime, tokenAddress: tokenAddress }); /* Increment the next stream id. */ (vars.mathErr, nextStreamId) = addUInt(nextStreamId, uint256(1)); require( vars.mathErr == MathError.NO_ERROR, "next stream id calculation error" ); require( IERC20(tokenAddress).transferFrom( msg.sender, address(this), deposit ), "token transfer failure" ); emit CreateStream( streamId, msg.sender, recipient, deposit, tokenAddress, startTime, stopTime ); return streamId; } struct WithdrawFromStreamLocalVars { MathError mathErr; } /** * @notice Withdraws from the contract to the recipient's account. * @dev Throws if the id does not point to a valid stream. * Throws if the caller is not the sender or the recipient of the stream. * Throws if the amount exceeds the available balance. * Throws if there is a token transfer failure. * @param streamId The id of the stream to withdraw tokens from. * @param amount The amount of tokens to withdraw. * @return bool true=success, otherwise false. */ function withdrawFromStream(uint256 streamId, uint256 amount) external override nonReentrant streamExists(streamId) onlySenderOrRecipient(streamId) returns (bool) { require(amount > 0, "amount is zero"); Types.Stream memory stream = streams[streamId]; WithdrawFromStreamLocalVars memory vars; uint256 balance = balanceOf(streamId, stream.recipient); require(balance >= amount, "amount exceeds the available balance"); (vars.mathErr, streams[streamId].remainingBalance) = subUInt( stream.remainingBalance, amount ); /** * `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know that `remainingBalance` is at least * as big as `amount`. */ assert(vars.mathErr == MathError.NO_ERROR); if (streams[streamId].remainingBalance == 0) delete streams[streamId]; require( IERC20(stream.tokenAddress).transfer(stream.recipient, amount), "token transfer failure" ); emit WithdrawFromStream(streamId, stream.recipient, amount); return true; } /** * @notice Cancels the stream and transfers the tokens back on a pro rata basis. * @dev Throws if the id does not point to a valid stream. * Throws if the caller is not the sender or the recipient of the stream. * Throws if there is a token transfer failure. * @param streamId The id of the stream to cancel. * @return bool true=success, otherwise false. */ function cancelStream(uint256 streamId) external override nonReentrant streamExists(streamId) onlySenderOrRecipient(streamId) returns (bool) { Types.Stream memory stream = streams[streamId]; uint256 senderBalance = balanceOf(streamId, stream.sender); uint256 recipientBalance = balanceOf(streamId, stream.recipient); delete streams[streamId]; IERC20 token = IERC20(stream.tokenAddress); if (recipientBalance > 0) require( token.transfer(stream.recipient, recipientBalance), "recipient token transfer failure" ); if (senderBalance > 0) require( token.transfer(stream.sender, senderBalance), "sender token transfer failure" ); emit CancelStream( streamId, stream.sender, stream.recipient, senderBalance, recipientBalance ); return true; } } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma experimental ABIEncoderV2; interface ITokenVesting { event Released( address indexed token, address vestingBeneficiary, uint256 amount ); event LogTokenAdded( address indexed token, address vestingBeneficiary, uint256 vestingPeriodInDays ); event LogBeneficiaryUpdated( address indexed token, address vestingBeneficiary ); struct VestingInfo { address vestingBeneficiary; uint256 totalBalance; uint256 beneficiariesCount; uint256 start; uint256 stop; } struct Beneficiary { address beneficiary; uint256 proportion; uint256 streamId; uint256 remaining; } function addToken( address _token, address[3] calldata _beneficiaries, uint256[3] calldata _proportions, uint256 _vestingPeriodInDays ) external; function release(address _token, address _beneficiary) external; function releaseableAmount(address _token) external view returns (uint256); function releaseableAmountByAddress(address _token, address _beneficiary) external view returns (uint256); function vestedAmount(address _token) external view returns (uint256); function getVestingInfo(address _token) external view returns (VestingInfo memory); function setVestingAddress( address _vestingBeneficiary, address _token, address _newVestingBeneficiary ) external; function setVestingReferral( address _vestingBeneficiary, address _token, address _vestingReferral ) external; function getAllTokensByBeneficiary(address _beneficiary) external view returns (address[] memory); function releaseAll(address _beneficiary) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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.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.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; } } pragma solidity =0.7.6; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-decision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 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(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } (MathError err1, uint256 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) internal pure returns (MathError, Exp memory) { (MathError error, uint256 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) internal pure returns (MathError, Exp memory) { (MathError error, uint256 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, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 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, uint256 scalar) internal pure returns (MathError, uint256) { (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, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (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, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 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(uint256 scalar, Exp memory divisor) internal pure 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, uint256 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(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (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) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 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, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } (MathError err2, uint256 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(uint256 a, uint256 b) internal pure 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 ) internal pure 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) internal pure 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) internal pure returns (uint256) { // 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) internal pure returns (bool) { return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo. } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } pragma solidity =0.7.6; /** * @title ERC-1620 Money Streaming Standard * @author Sablier * @dev See https://eips.ethereum.org/EIPS/eip-1620 */ interface IERC1620 { /** * @notice Emits when a stream is successfully created. */ event CreateStream( uint256 indexed streamId, address indexed sender, address indexed recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ); /** * @notice Emits when the recipient of a stream withdraws a portion or all their pro rata share of the stream. */ event WithdrawFromStream( uint256 indexed streamId, address indexed recipient, uint256 amount ); /** * @notice Emits when a stream is successfully cancelled and tokens are transferred back on a pro rata basis. */ event CancelStream( uint256 indexed streamId, address indexed sender, address indexed recipient, uint256 senderBalance, uint256 recipientBalance ); function balanceOf(uint256 streamId, address who) external view returns (uint256 balance); function getStream(uint256 streamId) external view returns ( address sender, address recipient, uint256 deposit, address token, uint256 startTime, uint256 stopTime, uint256 remainingBalance, uint256 ratePerSecond ); function createStream( address recipient, uint256 deposit, address tokenAddress, uint256 startTime, uint256 stopTime ) external returns (uint256 streamId); function withdrawFromStream(uint256 streamId, uint256 funds) external returns (bool); function cancelStream(uint256 streamId) external returns (bool); } pragma solidity =0.7.6; /** * @title Sablier Types * @author Sablier */ library Types { struct Stream { uint256 deposit; uint256 ratePerSecond; uint256 remainingBalance; uint256 startTime; uint256 stopTime; address recipient; address sender; address tokenAddress; bool isEntity; } } pragma solidity =0.7.6; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 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(uint256 a, uint256 b) internal pure returns (MathError, uint256) { 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(uint256 a, uint256 b) internal pure returns (MathError, uint256) { 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(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 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( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }
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). token The token targeted by the call. data The call data (encoded using abi.encode or one of its variants)./ 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. Return data is optional solhint-disable-next-line max-line-length
function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } }
12,569,759
./full_match/137/0xD12345Cd15352ef5d4259BD2a918Fcb6943ce7a4/sources/contracts/core/connext/helpers/StableSwap.sol
Swap two tokens using this pool assetIn the token the user wants to swap from assetOut the token the user wants to swap to amountIn the amount of tokens the user wants to swap from minAmountOut the min amount of tokens the user wants to swap to/
function swapExact( uint256 amountIn, address assetIn, address assetOut, uint256 minAmountOut, uint256 deadline ) external payable override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { uint8 tokenIndexFrom = getTokenIndex(assetIn); uint8 tokenIndexTo = getTokenIndex(assetOut); return swapStorage.swap(tokenIndexFrom, tokenIndexTo, amountIn, minAmountOut); }
4,729,537
./full_match/80001/0x6838b79FFb156c62334D79DE73d67dE850C424CB/sources/project:/contracts/Proxy/V1/NftMarketplaceERC1155ProxyV2.sol
Secondary listing business logic need to add additional checks
function listItem( address nftAddress, uint256 tokenId, uint256 amount, uint256 price ) external isNftTokenOwner(nftAddress, tokenId, msg.sender) { require(amount > 0, "Amount must be above zero"); if (price <= 0) { revert PriceMustBeAboveZero(); } IERC1155 nft = IERC1155(nftAddress); if (!nft.isApprovedForAll(msg.sender, address(this))) { revert NotApprovedForMarketplace(); } s_listings[nftAddress][msg.sender][tokenId] = Listing(price, amount, msg.sender); emit ItemListed(msg.sender, nftAddress, tokenId, amount, price); }
5,581,127
./full_match/1/0xDa71df48bacaAD3BF64237829a172d956a9A7749/sources/contracts/Sale.sol
calculate amount of tokens for available DAI DAIAmount - amount of DAI return amount of tokens to be sent to contributor/
function getTokenAmount(uint DAIAmount) public view returns(uint256){ uint256 _rate = _determineRate(); return DAIAmount.mul(1e18).div(_rate); }
9,740,963
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import { CONTROLLER, ADMIN, EXCHANGE_RATE_FACTOR, ONE_HUNDRED_PERCENT } from "./data.sol"; import { ITTokenStrategy } from "./strategies/ITTokenStrategy.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // Utils import { Address } from "@openzeppelin/contracts/utils/Address.sol"; // Interfaces import { ITToken } from "./ITToken.sol"; import { ICErc20 } from "../../shared/interfaces/ICErc20.sol"; // Libraries import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { RolesLib } from "../../contexts2/access-control/roles/RolesLib.sol"; import { NumbersLib } from "../../shared/libraries/NumbersLib.sol"; // Storage import "./storage.sol" as Storage; /** * @notice This contract represents a lending pool for an asset within Teller protocol. * @author [email protected] */ contract TToken_V1 is ITToken { function() pure returns (Storage.Store storage) private constant s = Storage.store; /* Modifiers */ /** * @notice Checks if the LP is restricted or has the CONTROLLER role. * * The LP being restricted means that only the Teller protocol may * lend/borrow funds. */ modifier notRestricted { require( !s().restricted || RolesLib.hasRole(CONTROLLER, _msgSender()), "Teller: platform restricted" ); _; } /* Public Functions */ /** * @notice it returns the decimal places of the respective TToken * @return decimals of the token */ function decimals() public view override returns (uint8) { return s().decimals; } /** * @notice The token that is the underlying assets for this Teller token. * @return ERC20 token that is the underl */ function underlying() public view override returns (ERC20) { return s().underlying; } /** * @notice The balance of an {account} denoted in underlying value. * @param account Address to calculate the underlying balance. * @return balance_ the balance of the account */ function balanceOfUnderlying(address account) public override returns (uint256) { return _valueInUnderlying(balanceOf(account), exchangeRate()); } /** * @notice It calculates the current exchange rate for a whole Teller Token based of the underlying token balance. * @return rate_ The current exchange rate. */ function exchangeRate() public override returns (uint256 rate_) { if (totalSupply() == 0) { return EXCHANGE_RATE_FACTOR; } rate_ = (currentTVL() * EXCHANGE_RATE_FACTOR) / totalSupply(); } /** * @notice It calculates the total supply of the underlying asset. * @return totalSupply_ the total supply denoted in the underlying asset. */ function totalUnderlyingSupply() public override returns (uint256) { bytes memory data = _delegateStrategy( abi.encodeWithSelector( ITTokenStrategy.totalUnderlyingSupply.selector ) ); return abi.decode(data, (uint256)); } /** * @notice It calculates the market state values across a given markets. * @notice Returns values that represent the global state across the market. * @return totalSupplied Total amount of the underlying asset supplied. * @return totalBorrowed Total amount borrowed through loans. * @return totalRepaid The total amount repaid till the current timestamp. * @return totalInterestRepaid The total amount interest repaid till the current timestamp. * @return totalOnLoan Total amount currently deployed in loans. */ function getMarketState() external override returns ( uint256 totalSupplied, uint256 totalBorrowed, uint256 totalRepaid, uint256 totalInterestRepaid, uint256 totalOnLoan ) { totalSupplied = totalUnderlyingSupply(); totalBorrowed = s().totalBorrowed; totalRepaid = s().totalRepaid; totalInterestRepaid = s().totalInterestRepaid; totalOnLoan = totalBorrowed - totalRepaid; } /** * @notice Calculates the current Total Value Locked, denoted in the underlying asset, in the Teller Token pool. * @return tvl_ The value locked in the pool. * * Note: This value includes the amount that is on loan (including ones that were sent to EOAs). */ function currentTVL() public override returns (uint256 tvl_) { tvl_ += totalUnderlyingSupply(); tvl_ += s().totalBorrowed; tvl_ -= s().totalRepaid; } /** * @notice It validates whether supply to debt (StD) ratio is valid including the loan amount. * @param newLoanAmount the new loan amount to consider the StD ratio. * @return ratio_ Whether debt ratio for lending pool is valid. */ function debtRatioFor(uint256 newLoanAmount) external override returns (uint16 ratio_) { uint256 onLoan = s().totalBorrowed - s().totalRepaid; uint256 supplied = totalUnderlyingSupply() + onLoan; if (supplied > 0) { ratio_ = NumbersLib.ratioOf(onLoan + newLoanAmount, supplied); } } /** * @notice Called by the Teller Diamond contract when a loan has been taken out and requires funds. * @param recipient The account to send the funds to. * @param amount Funds requested to fulfil the loan. */ function fundLoan(address recipient, uint256 amount) external override authorized(CONTROLLER, _msgSender()) { // If TToken is not holding enough funds to cover the loan, call the strategy to try to withdraw uint256 balance = s().underlying.balanceOf(address(this)); if (balance < amount) { _delegateStrategy( abi.encodeWithSelector( ITTokenStrategy.withdraw.selector, amount - balance ) ); } // Increase total borrowed amount s().totalBorrowed += amount; // Transfer tokens to recipient SafeERC20.safeTransfer(s().underlying, recipient, amount); } /** * @notice Called by the Teller Diamond contract when a loan has been repaid. * @param amount Funds deposited back into the pool to repay the principal amount of a loan. * @param interestAmount Interest value paid into the pool from a loan. */ function repayLoan(uint256 amount, uint256 interestAmount) external override authorized(CONTROLLER, _msgSender()) { s().totalRepaid += amount; s().totalInterestRepaid += interestAmount; } /** * @notice Deposit underlying token amount into LP and mint tokens. * @param amount The amount of underlying tokens to use to mint. * @return Amount of TTokens minted. */ function mint(uint256 amount) external override notRestricted returns (uint256) { require(amount > 0, "Teller: cannot mint 0"); require( amount <= s().underlying.balanceOf(_msgSender()), "Teller: insufficient underlying" ); // Calculate amount of tokens to mint uint256 mintAmount = _valueOfUnderlying(amount, exchangeRate()); // Transfer tokens from lender SafeERC20.safeTransferFrom( s().underlying, _msgSender(), address(this), amount ); // Mint Teller token value of underlying _mint(_msgSender(), mintAmount); emit Mint(_msgSender(), mintAmount, amount); return mintAmount; } /** * @notice Redeem supplied Teller token underlying value. * @param amount The amount of Teller tokens to redeem. */ function redeem(uint256 amount) external override { require(amount > 0, "Teller: cannot withdraw 0"); require( amount <= balanceOf(_msgSender()), "Teller: redeem amount exceeds balance" ); // Accrue interest and calculate exchange rate uint256 underlyingAmount = _valueInUnderlying(amount, exchangeRate()); require( underlyingAmount <= totalUnderlyingSupply(), "Teller: redeem ttoken lp not enough supply" ); // Burn Teller Tokens and transfer underlying _redeem(amount, underlyingAmount); } /** * @notice Redeem supplied underlying value. * @param amount The amount of underlying tokens to redeem. */ function redeemUnderlying(uint256 amount) external override { require(amount > 0, "Teller: cannot withdraw 0"); require( amount <= totalUnderlyingSupply(), "Teller: redeem ttoken lp not enough supply" ); // Accrue interest and calculate exchange rate uint256 rate = exchangeRate(); uint256 tokenValue = _valueOfUnderlying(amount, rate); // Make sure sender has adequate balance require( tokenValue <= balanceOf(_msgSender()), "Teller: redeem amount exceeds balance" ); // Burn Teller Tokens and transfer underlying _redeem(tokenValue, amount); } /** * @dev Redeem an {amount} of Teller Tokens and transfers {underlyingAmount} to the caller. * @param amount Total amount of Teller Tokens to burn. * @param underlyingAmount Total amount of underlying asset tokens to transfer to caller. * * This function should only be called by {redeem} and {redeemUnderlying} after the exchange * rate and both token values have been calculated to use. */ function _redeem(uint256 amount, uint256 underlyingAmount) internal { // Burn Teller tokens _burn(_msgSender(), amount); // Make sure enough funds are available to redeem _delegateStrategy( abi.encodeWithSelector( ITTokenStrategy.withdraw.selector, underlyingAmount ) ); // Transfer funds back to lender SafeERC20.safeTransfer(s().underlying, _msgSender(), underlyingAmount); emit Redeem(_msgSender(), amount, underlyingAmount); } /** * @notice Rebalances the funds controlled by Teller Token according to the current strategy. * * See {TTokenStrategy}. */ function rebalance() public override { _delegateStrategy( abi.encodeWithSelector(ITTokenStrategy.rebalance.selector) ); } /** * @notice Sets a new strategy to use for balancing funds. * @param strategy Address to the new strategy contract. Must implement the {ITTokenStrategy} interface. * @param initData Optional data to initialize the strategy. * * Requirements: * - Sender must have ADMIN role */ function setStrategy(address strategy, bytes calldata initData) external override authorized(ADMIN, _msgSender()) { require( ERC165Checker.supportsInterface( strategy, type(ITTokenStrategy).interfaceId ), "Teller: strategy does not support ITTokenStrategy" ); s().strategy = strategy; if (initData.length > 0) { _delegateStrategy(initData); } } /** * @notice Gets the strategy used for balancing funds. * @return address of the strategy contract */ function getStrategy() external view override returns (address) { return s().strategy; } /** * @notice Sets the restricted state of the platform. * @param state boolean value that resembles the platform's state */ function restrict(bool state) public override authorized(ADMIN, _msgSender()) { s().restricted = state; } /** * @notice it initializes the Teller Token * @param admin address of the admin to the respective Teller Token * @param underlying address of the ERC20 token */ function initialize(address admin, address underlying) external override initializer { require( Address.isContract(msg.sender), "Teller: controller not contract" ); require( Address.isContract(underlying), "Teller: underlying token not contract" ); RolesLib.grantRole(CONTROLLER, msg.sender); RolesLib.grantRole(ADMIN, admin); s().underlying = ERC20(underlying); __ERC20_init( string(abi.encodePacked("Teller ", s().underlying.name())), string(abi.encodePacked("t", s().underlying.symbol())) ); s().decimals = s().underlying.decimals(); // Platform restricted by default s().restricted = true; } /** * @notice it retrieves the value of the underlying token * @param amount the amount of tokens to calculate the value of * @param rate the exchangeRate() to divide with the amount * exchange_rate_factor * @return value_ the underlying value of the token amount */ function _valueOfUnderlying(uint256 amount, uint256 rate) internal pure returns (uint256 value_) { value_ = (amount * EXCHANGE_RATE_FACTOR) / rate; } /** * @notice it retrives the value in the underlying tokens * */ function _valueInUnderlying(uint256 amount, uint256 rate) internal pure returns (uint256 value_) { value_ = (amount * (rate)) / EXCHANGE_RATE_FACTOR; } /** * @notice Delegates data to call on the strategy contract. * @param callData Data to call the strategy contract with. * * Requirements: * - Sender must have ADMIN role */ function _delegateStrategy(bytes memory callData) internal returns (bytes memory) { return Address.functionDelegateCall(s().strategy, callData); } }
Delegates data to call on the strategy contract. callData Data to call the strategy contract with. Requirements: - Sender must have ADMIN role/
function _delegateStrategy(bytes memory callData) internal returns (bytes memory) { return Address.functionDelegateCall(s().strategy, callData); }
6,355,638
./partial_match/1/0x43eA73168B8f192dBDEC088DA29F2C5E517f6fcB/sources/contracts-verify/KUMASwap.sol
See {Pausable-_pause} can only be called by the KUMA_SWAP_PAUSE_ROLE/
function pause() external onlyRole(Roles.KUMA_SWAP_PAUSE_ROLE.toGranularRole(_riskCategory)) { _pause(); }
15,921,096
./partial_match/1/0x9460b380c57F65e8AFc4bA3518F643A526640F26/sources/contracts/protocol/libraries/logic/ReserveLogic.sol
Updates the liquidity cumulative index and the variable borrow index. reserve The reserve object reserveCache The caching layer for the reserve data/
function updateState( DataTypes.ReserveData storage reserve, DataTypes.ReserveCache memory reserveCache ) internal { _updateIndexes(reserve, reserveCache); _accrueToTreasury(reserve, reserveCache); }
4,203,432
./partial_match/4/0x18Bc87924d06DADFA8989692d4078F7fF87aF4Cc/sources/Escrow.sol
/ call function to base address for function signature of underlying
function _valueOfIn( address baseAddress, address quoteAddress, uint256 baseAmount ) internal view returns (uint256) { bool success; bytes memory returnData; (success, returnData) = baseAddress.staticcall( abi.encodeWithSignature("exchangeRateStored()") ); if (returnData.length > 0) { uint8 cTokenDecimals = CErc20Interface(baseAddress).decimals(); uint256 exchangeRate = abi.decode(returnData, (uint256)); uint256 diffFactor = uint256(10)**uint256(18).diff(uint256(cTokenDecimals)); if (cTokenDecimals > uint256(18)) { exchangeRate = exchangeRate.mul(diffFactor); exchangeRate = exchangeRate.div(diffFactor); } uint8 assetDecimals; if (baseAddress == _getSettings().CETH_ADDRESS()) { baseAddress = _getSettings().ETH_ADDRESS(); assetDecimals = uint8(18); baseAddress = CErc20Interface(baseAddress).underlying(); assetDecimals = ERC20Detailed(baseAddress).decimals(); } baseAmount = baseAmount.mul(exchangeRate).div(uint256(10)**assetDecimals); } return _getSettings().chainlinkAggregator().valueFor( baseAddress, quoteAddress, baseAmount ); }
8,596,824
pragma solidity ^0.4.0; /** * @title Pairing * @dev BN128 pairing operations. Taken from https://github.com/JacobEberhardt/ZoKrates/blob/da5b13f845145cf43d555c7741158727ef0018a2/zokrates_core/src/verification.rs. */ library Pairing { /* * Structs */ struct G1Point { uint x; uint y; } struct G2Point { uint[2] x; uint[2] y; } /* * Internal functions */ /** * @return The generator of G1. */ function P1() internal pure returns (G1Point) { return G1Point(1, 2); } /** * @return The generator of G2. */ function P2() internal pure returns (G2Point) { return G2Point({ x: [ 11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781 ], y: [ 4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930 ] }); } /** * @dev Hashes a message into G1. * @param _message Message to hash. * @return Hashed G1 point. */ function hashToG1(bytes _message) internal returns (G1Point) { uint256 h = uint256(keccak256(_message)); return curveMul(P1(), h); } /** * @dev Negates a point in G1. * @param _point Point to negate. * @return The negated point. */ function negate(G1Point _point) internal pure returns (G1Point) { uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; if (_point.x == 0 && _point.y == 0) { return G1Point(0, 0); } return G1Point(_point.x, q - (_point.y % q)); } /** * @dev Computes the pairing check e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 * @param _g1points List of points in G1. * @param _g2points List of points in G2. * @return True if pairing check succeeds. */ function pairing(G1Point[] _g1points, G2Point[] _g2points) internal returns (bool) { require(_g1points.length == _g2points.length, "Point count mismatch."); uint elements = _g1points.length; uint inputSize = elements * 6; uint[] memory input = new uint[](inputSize); for (uint i = 0; i < elements; i++) { input[i * 6 + 0] = _g1points[i].x; input[i * 6 + 1] = _g1points[i].y; input[i * 6 + 2] = _g2points[i].x[0]; input[i * 6 + 3] = _g2points[i].x[1]; input[i * 6 + 4] = _g2points[i].y[0]; input[i * 6 + 5] = _g2points[i].y[1]; } uint[1] memory out; bool success; assembly { success := call(sub(gas, 2000), 8, 0, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success, "Pairing operation failed."); return out[0] != 0; } /** * @dev Convenience method for pairing check on two pairs. * @param _g1point1 First point in G1. * @param _g2point1 First point in G2. * @param _g1point2 Second point in G1. * @param _g2point2 Second point in G2. * @return True if the pairing check succeeds. */ function pairing2( G1Point _g1point1, G2Point _g2point1, G1Point _g1point2, G2Point _g2point2 ) internal returns (bool) { G1Point[] memory g1points = new G1Point[](2); G2Point[] memory g2points = new G2Point[](2); g1points[0] = _g1point1; g1points[1] = _g1point2; g2points[0] = _g2point1; g2points[1] = _g2point2; return pairing(g1points, g2points); } /* * Private functions */ /** * @dev Multiplies a point in G1 by a scalar. * @param _point G1 point to multiply. * @param _scalar Scalar to multiply. * @return The resulting G1 point. */ function curveMul(G1Point _point, uint _scalar) private returns (G1Point) { uint[3] memory input; input[0] = _point.x; input[1] = _point.y; input[2] = _scalar; bool success; G1Point memory result; assembly { success := call(sub(gas, 2000), 7, 0, input, 0x80, result, 0x60) } require(success, "Point multiplication failed."); return result; } }
Multiplies a point in G1 by a scalar. _point G1 point to multiply. _scalar Scalar to multiply. return The resulting G1 point./
function curveMul(G1Point _point, uint _scalar) private returns (G1Point) { uint[3] memory input; input[0] = _point.x; input[1] = _point.y; input[2] = _scalar; bool success; G1Point memory result; assembly { success := call(sub(gas, 2000), 7, 0, input, 0x80, result, 0x60) } require(success, "Point multiplication failed."); return result; }
15,808,063
./full_match/1/0x2dD4242C894d20060b162747362aF1721Fa7f5d5/sources/contracts/MAGIStaker.sol
external call for claim reward function
function claimReward() public nonReentrant returns (uint) { return _claimReward(msg.sender); }
3,189,527
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } pragma solidity >=0.8.0 <0.9.0; // =========================================================================================== /** * @title SpaceConvicts * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract SpaceConvicts is ERC721Enumerable, Ownable { using Strings for uint256; using Address for address; struct Conf { bool mintEnabled; uint8 perMint; uint16 perAccount; uint16 perAccountWl; uint16 supply; uint16 maxNFTs; uint64 price; bool whitelistEnabled; address whitelister; uint256 honorary; uint256 honoraryIDs; uint256 honoraryIDsStart; } address private controller; string private defaultURI; string private defaultURIh; string private baseURI; string private baseURIh; string private metaURI; uint256 public startingIndex; Conf private conf; struct ExtensionContract { string name; address addr; } mapping (uint => ExtensionContract) private extensionContracts; /** * @notice Setup ERC721 and initial config */ constructor( string memory name, string memory symbol, string memory _defaultURI, string memory _defaultURIh ) ERC721(name, symbol) { conf = Conf( false, // mintEnabled: if minting is enabled 10, // perMint: max number of NFTs that can be minted per TX 20, // perAccount: max number of NFTs that can be minted per ETH address 10, // perAccountWL: max number of NFTs that can be minted per ETH address during WL pre-sale 200, // supply: reserved NFTs 9999, // maxNFTs: maximum supply 60000000000000000, // price: price per NFT in wei true, // whitelistEnabled: if whitelist is required for minting 0xDbCADD59B8387B1279712967fc93e4d5b2aD5B3a, // whitelister: the address that signs the whitelisted transactions 25, // honorary amount 100000, // honorary id counter 100000 // honorary start id ); defaultURI = _defaultURI; defaultURIh = _defaultURIh; } function getExtensions(uint extensionId) public view returns (string memory, address) { return (extensionContracts[extensionId].name, extensionContracts[extensionId].addr); } function setExtensions(uint extensionId, string memory name, address addr) public onlyOwner { extensionContracts[extensionId] = ExtensionContract(name, addr); } /** * @notice Mint reserved SpaceConvicts. * @param accounts Array of accounts to receive reserves. * @param start Index to start minting at. * @dev Utilize unchecked {} and calldata for gas savings. */ function mintReserved(address[] calldata accounts, uint16 start) public onlyOwner { address[] memory _accounts = accounts; unchecked { for (uint8 i = 0; i < _accounts.length; i++) { _safeMint(_accounts[i], start + i); } } } /** * @notice Take eth out of the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @notice Mint SpaceConvicts. * @param amount Number of SpaceConvicts to mint. * @dev Utilize unchecked {} and calldata for gas savings. */ function mint(uint256 amount) public payable { require(conf.mintEnabled, "Minting is disabled."); require(!conf.whitelistEnabled, "Whitelist sale only"); require( conf.supply + amount <= conf.maxNFTs, "Amount exceeds maximum supply of Test." ); require( balanceOf(msg.sender) + amount <= conf.perAccount, "Amount exceeds current maximum mints per account." ); require( amount <= conf.perMint, "Amount exceeds current maximum SpaceConvicts per mint." ); require( conf.price * amount <= msg.value, "Ether value sent is not correct." ); uint16 supply = conf.supply; unchecked { for (uint16 i = 0; i < amount; i++) { _safeMint(msg.sender, supply++); } } conf.supply = supply; } function toString(bytes memory data) public pure returns(string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } function mintWhitelist(uint256 amount, bytes32 msgh, uint8 v, bytes32 r, bytes32 s) public payable { require(conf.mintEnabled, "Minting is disabled."); require(conf.whitelistEnabled, "Whitelist sale has ended."); require( conf.supply + amount <= conf.maxNFTs, "Amount exceeds maximum supply of Test." ); require( balanceOf(msg.sender) + amount <= conf.perAccountWl, "Amount exceeds current maximum mints per account." ); require( amount <= conf.perMint, "Amount exceeds current maximum SpaceConvicts per mint." ); require( conf.price * amount <= msg.value, "Ether value sent is not correct." ); string memory collector = toString(abi.encodePacked(msg.sender)); require( isWhitelisted(collector, msgh, v, r, s), "Address is not whitelisted" ); uint16 supply = conf.supply; unchecked { for (uint16 i = 0; i < amount; i++) { _safeMint(msg.sender, supply++); } } conf.supply = supply; } // Function for minting honorary NFTs to partners function mint_h(address _to, uint256 amount) external onlyOwner { require( _to != address(0), "Zero address error"); require( amount <= conf.honorary, "Exceeds honorary supply" ); for(uint256 i; i < amount; i++){ _safeMint( _to, conf.honoraryIDs++); conf.honorary --; } } /** * @dev Returns minting state. */ function getMintEnabled() public view returns (bool) { return conf.mintEnabled; } /** * @notice Toggles minting state. */ function toggleMintEnabled() public onlyOwner { conf.mintEnabled = !conf.mintEnabled; } /** * @notice Toggles minting state. FIXEM: TEST THIS */ function changeMintPrice(uint64 _price) public onlyOwner { conf.price = _price; } /** * @dev Returns minting state. */ function getMintPrice() public view returns (uint64) { return conf.price; } /** * @notice Returns max SpaceConvicts per mint. */ function getPerMint() public view returns (uint8) { return conf.perMint; } /** * @notice Sets max SpaceConvicts per mint. */ function setPerMint(uint8 _perMint) public onlyOwner { conf.perMint = _perMint; } /** * @notice Returns max mints per account. */ function getPerAccount() public view returns (uint16) { return conf.perAccount; } /** * @notice Sets max mints per account. */ function setPerAccountWl(uint16 _perAccountWl) public onlyOwner { conf.perAccountWl = _perAccountWl; } /** * @notice Returns max mints per account. */ function getPerAccountWl() public view returns (uint16) { return conf.perAccountWl; } /** * @notice Sets max mints per account. */ function setPerAccount(uint16 _perAccount) public onlyOwner { conf.perAccount = _perAccount; } /** * @notice Set base URI. */ function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function setBaseURIh(string memory _baseURIh) public onlyOwner { baseURIh = _baseURIh; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist."); if (bytes(baseURI).length == 0) { return string(abi.encodePacked(defaultURI, (tokenId + 1).toString())); } else { if (tokenId < conf.honoraryIDsStart){ uint256 revealedId = (tokenId + startingIndex) % conf.maxNFTs + 1; return string(abi.encodePacked(baseURI, revealedId.toString())); } else { if (bytes(baseURIh).length == 0) { return string(abi.encodePacked(defaultURIh, tokenId.toString())); } else { return string(abi.encodePacked(baseURIh, tokenId.toString())); } } } } /** * @dev Returns whitelist state. */ function getWhitelistEnabled() public view returns (bool) { return conf.whitelistEnabled; } /** * @notice Toggles whitelist state. */ function toggleWhitelistEnabled() public onlyOwner { conf.whitelistEnabled = !conf.whitelistEnabled; } function isWhitelisted(string memory collector, bytes32 msgh, uint8 v, bytes32 r, bytes32 s) public view returns (bool) { if (keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n" , "42", collector)) != msgh){return false;} if (ecrecover(msgh, v, r, s) != conf.whitelister){return false;} return true; } function setRandomStartingIndex() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndex = uint(blockhash(block.number-1)) % (conf.maxNFTs - 1); if (startingIndex == 0) { startingIndex = startingIndex + 1; } } }
Sets max mints per account./
function setPerAccountWl(uint16 _perAccountWl) public onlyOwner { conf.perAccountWl = _perAccountWl; }
10,972,444
./full_match/5/0x777d8d5d76b3abE983dE78bC6c2a526b62381f64/sources/NCore.flat.sol
Close DCA. _srcToken Source token address. _chainId Chain id for the destination token. _destToken Destination token address. _ibStrategy Strategy address./
function closeDCA(address _srcToken, uint256 _chainId, address _destToken, address _ibStrategy) external resolverFree { NDCA(DCA).closeDCA(msg.sender, _srcToken, _chainId, _destToken, _ibStrategy); _storeDCA(msg.sender, histDetail(_srcToken, _chainId, _destToken, _ibStrategy, uint40(block.timestamp), 1)); }
11,585,846
/// @title Folder -- Folder Management /// @author BloodMoon - <[email protected]> /// @version 0.1 /// @date 2021-12-3 pragma solidity ^0.8.0; contract List{ struct ItemList { uint256 Id; string Name; address Author; bool Status; // uint256 FatherNode; string Class; string Tag; string Description; uint256[] CourseIds; uint256[] ExperimentIds; uint256 Time; uint256 BlockNum; } struct LessonList { uint256 Id; string Name; address Author; bool Status; // uint256 FatherNode; string Class; string Tag; string Description; uint256 Time; uint256 BlockNum; } struct StationList { uint256 Id; string Name; address Author; bool Status; // uint256 FatherNode; string Class; string Tag; string Description; uint256 Time; uint256 BlockNum; } //基本存储信息 StationList[] stationLists; LessonList[] lessonLists; ItemList[] itemLists; //列表结构信息 mapping(uint256=>uint256[]) ListToLesson; mapping(uint256=>uint256[]) LessonToItem; //打分信息 mapping(uint256 => mapping(address => uint256)) stationScores; mapping(uint256 => mapping(address => uint256)) LessonScores; mapping(uint256 => mapping(address => uint256)) ItemScores; mapping(uint256 => address[]) arrayStationScores; mapping(uint256 => address[]) arrayLessonScores; mapping(uint256 => address[]) arrayItemScores; modifier StationListAuthorCheck(uint256 Id){ require(stationLists[Id].Author==msg.sender); _; } modifier LessonListAuthorCheck(uint256 Id){ require(lessonLists[Id].Author==msg.sender); _; } modifier ItemListAuthorCheck(uint256 Id){ require(itemLists[Id].Author==msg.sender); _; } //=================增=================== function addStationList(string memory _name, string memory _tag, string memory _class, string memory _description) public returns (bool){ uint nextId = stationLists.length; StationList memory stationList = StationList({ Id : nextId, Name : _name, Author : msg.sender, Status : true, Class : _class, Tag : _tag, Description : _description, Time : block.timestamp, BlockNum: block.number } ); stationLists.push(stationList); return true; } function addLessonList(string memory _name, string memory _tag, string memory _class, string memory _description) public returns (bool){ uint nextId = lessonLists.length; LessonList memory lessonList = LessonList({ Id : nextId, Name : _name, Author : msg.sender, Status : true, Class : _class, Tag : _tag, Description : _description, Time : block.timestamp, BlockNum: block.number } ); lessonLists.push(lessonList); return true; } function addItemList(string memory _name, string memory _tag, string memory _class, string memory _description) public returns (bool){ uint nextId = itemLists.length; ItemList memory itemList = ItemList({ Id : nextId, Name : _name, Author : msg.sender, Status : true, Class : _class, Tag : _tag, Description : _description, Time : block.timestamp, BlockNum: block.number, CourseIds:new uint256[](0), ExperimentIds:new uint256[](0) } ); itemLists.push(itemList); return true; } function addLessonForStation(uint256 stationIndex,uint256 lessonIndex) public returns(bool){ ListToLesson[stationIndex].push(lessonIndex); return true; } function addItemForLesson(uint256 lessonIndex,uint256 itemIndex) public returns(bool){ LessonToItem[lessonIndex].push(itemIndex); return true; } function addCourseToItem(uint256 _itemId,uint256 _courseId) public returns(bool){ itemLists[_itemId].CourseIds.push(_courseId); return true; } function addExperimentToItem(uint256 _itemId,uint256 _experimentId) public returns(bool){ itemLists[_itemId].ExperimentIds.push(_experimentId); return true; } //=================改=================== function modifyStationInfo(uint256 _id,string memory _name, string memory _tag, string memory _class, string memory _description) public returns(bool){ stationLists[_id].Name=_name; stationLists[_id].Tag=_tag; stationLists[_id].Class=_class; stationLists[_id].Description=_description; return true; } function modifyLessonInfo(uint256 _id,string memory _name, string memory _tag, string memory _class, string memory _description) public returns(bool){ lessonLists[_id].Name=_name; lessonLists[_id].Tag=_tag; lessonLists[_id].Class=_class; lessonLists[_id].Description=_description; return true; } function modifyItemInfo(uint256 _id,string memory _name, string memory _tag, string memory _class, string memory _description) public returns(bool){ itemLists[_id].Name=_name; itemLists[_id].Tag=_tag; itemLists[_id].Class=_class; itemLists[_id].Description=_description; return true; } //=================删=================== function removeLessonIndexFromStation(uint256 _stationId, uint256 _lessonIndex) StationListAuthorCheck(_stationId) public { uint length = ListToLesson[_stationId].length; if (_lessonIndex == length - 1) { ListToLesson[_stationId].pop(); } else { ListToLesson[_stationId][_lessonIndex] = ListToLesson[_stationId][length - 1]; ListToLesson[_stationId].pop(); } } function removeLessonIdValueFromStation(uint256 _stationId, uint256 _lessonId) StationListAuthorCheck(_stationId) public { uint delIndex; for (uint i = 0; i < ListToLesson[_stationId].length; i++) { if (ListToLesson[_stationId][i] == _lessonId) { delIndex = i; } } removeLessonIndexFromStation(_stationId, delIndex); } function removeItemIndexFromLesson(uint256 _lessonId, uint256 _itemIndex) LessonListAuthorCheck(_lessonId) public { uint length = LessonToItem[_lessonId].length; if (_itemIndex == length - 1) { LessonToItem[_lessonId].pop(); } else { LessonToItem[_lessonId][_itemIndex] = LessonToItem[_lessonId][length - 1]; LessonToItem[_lessonId].pop(); } } function removeItemIdValueFromLesson(uint256 _lessonId, uint256 _itemId) LessonListAuthorCheck(_lessonId) public { uint delIndex; for (uint i = 0; i < LessonToItem[_lessonId].length; i++) { if (LessonToItem[_lessonId][i] == _itemId) { delIndex = i; } } removeItemIndexFromLesson(_lessonId, delIndex); } function removeCourseIndexFromItem(uint256 _itemId, uint256 _index) ItemListAuthorCheck(_itemId) public { uint length = itemLists[_itemId].CourseIds.length; if (_index == length - 1) { itemLists[_itemId].CourseIds.pop(); } else { itemLists[_itemId].CourseIds[_index] = itemLists[_itemId].CourseIds[length - 1]; itemLists[_itemId].CourseIds.pop(); } } function removeCourseValueFromItem(uint256 _itemId, uint256 _value) ItemListAuthorCheck(_itemId) public { uint delIndex; for (uint i = 0; i < itemLists[_itemId].CourseIds.length; i++) { if (itemLists[_itemId].CourseIds[i] == _value) { delIndex = i; } } removeCourseIndexFromItem(_itemId, delIndex); } function removeExperimentIndexFromItem(uint256 _itemId, uint256 _index) ItemListAuthorCheck(_itemId) public { uint length = itemLists[_itemId].ExperimentIds.length; if (_index == length - 1) { itemLists[_itemId].ExperimentIds.pop(); } else { itemLists[_itemId].ExperimentIds[_index] = itemLists[_itemId].ExperimentIds[length - 1]; itemLists[_itemId].ExperimentIds.pop(); } } function removeExperimentValueFromItem(uint256 _itemId, uint256 _value) ItemListAuthorCheck(_itemId) public { uint delIndex; for (uint i = 0; i < itemLists[_itemId].ExperimentIds.length; i++) { if (itemLists[_itemId].ExperimentIds[i] == _value) { delIndex = i; } } removeExperimentIndexFromItem(_itemId, delIndex); } //=================查=================== function getLessonsFromStationId(uint256 _stationId) public view returns(LessonList[] memory){ uint256[] memory lessonIds=ListToLesson[_stationId]; uint length=lessonIds.length; LessonList[] memory retLessonList=new LessonList[](length); for(uint i=0;i<length;i++){ retLessonList[i]=lessonLists[lessonIds[i]]; } return retLessonList; } function getItemsFromLessonId(uint256 _lessonId) public view returns(ItemList[] memory){ uint256[] memory itemIds=LessonToItem[_lessonId]; uint length=itemIds.length; ItemList[] memory retItemList=new ItemList[](length); for(uint i=0;i<length;i++){ retItemList[i]=itemLists[itemIds[i]]; } return retItemList; } function getCoursesIdsFromItemId(uint256 _itemId) public view returns(uint256[] memory){ uint256[] memory ids=itemLists[_itemId].CourseIds; return ids; } function getExperimentIdsFromItemId(uint256 _itemId) public view returns(uint256[] memory){ uint256[] memory ids=itemLists[_itemId].ExperimentIds; return ids; } function getAllStation() public view returns(StationList[] memory){ return stationLists; } function getStationFromId(uint256 _id) public view returns(StationList memory){ return stationLists[_id]; } function getLessonnFromId(uint256 _id) public view returns(LessonList memory){ return lessonLists[_id]; } function getItemFromId(uint256 _id) public view returns(ItemList memory){ return itemLists[_id]; } function getAllLesson() public view returns(LessonList[] memory){ return lessonLists; } function getAllItem() public view returns(ItemList[] memory){ return itemLists; } //=================打分=================== function addScoreForStation(uint256 _stationId,uint256 score) public{ require(score <= 100 && score >= 0, "score overflow"); if(checkIfExist(msg.sender,arrayStationScores[_stationId])){ stationScores[_stationId][msg.sender] = score; } else{ stationScores[_stationId][msg.sender] = score; arrayStationScores[_stationId].push(msg.sender); } } function addScoreForLesson(uint256 _id,uint256 score) public{ require(score <= 100 && score >= 0, "score overflow"); if(checkIfExist(msg.sender,arrayLessonScores[_id])){ LessonScores[_id][msg.sender] = score; } else{ LessonScores[_id][msg.sender] = score; arrayLessonScores[_id].push(msg.sender); } } function addScoreForItem(uint256 _id,uint256 score) public{ require(score <= 100 && score >= 0, "score overflow"); if(checkIfExist(msg.sender,arrayItemScores[_id])){ ItemScores[_id][msg.sender] = score; } else{ ItemScores[_id][msg.sender] = score; arrayItemScores[_id].push(msg.sender); } } //=================打分查询=================== function getMyStationScore(uint256 _id) public view returns(uint256){ return stationScores[_id][msg.sender]; } function getMyLessonScore(uint256 _id) public view returns(uint256){ return LessonScores[_id][msg.sender]; } function getMyItemScore(uint256 _id) public view returns(uint256){ return ItemScores[_id][msg.sender]; } function calculateStationScore(uint256 _id) public view returns(uint256){ uint256 sum = 0; uint256 length = arrayStationScores[_id].length; for (uint i = 0; i < length; i++) { uint256 score = stationScores[_id][arrayStationScores[_id][i]]; sum = sum + score; } return sum / length; } function calculateLessonScore(uint256 _id) public view returns(uint256){ uint256 sum = 0; uint256 length = arrayLessonScores[_id].length; for (uint i = 0; i < length; i++) { uint256 score = LessonScores[_id][arrayLessonScores[_id][i]]; sum = sum + score; } return sum / length; } function calculateItemScore(uint256 _id) public view returns(uint256){ uint256 sum = 0; uint256 length = arrayItemScores[_id].length; for (uint i = 0; i < length; i++) { uint256 score = ItemScores[_id][arrayItemScores[_id][i]]; sum = sum + score; } return sum / length; } //=================数组工具1=================== function checkIfExist(address adrs, address[] memory adrss) public returns (bool){ for (uint i = 0; i < adrss.length; i++) { if (adrss[i] == adrs) { return true; } } return false; } }
=================改===================
function modifyStationInfo(uint256 _id,string memory _name, string memory _tag, string memory _class, string memory _description) public returns(bool){ stationLists[_id].Name=_name; stationLists[_id].Tag=_tag; stationLists[_id].Class=_class; stationLists[_id].Description=_description; return true; }
5,499,010
pragma solidity ^0.4.24; 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) { uint256 c = a / b; 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; } } contract owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { totalSupply = 200000000; balanceOf[msg.sender] = totalSupply; name = "CTB"; symbol = "ȼ"; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to].add(_value) > balanceOf[_to]); uint previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] = balanceOf[_from].sub(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract CTBCoin is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() TokenERC20() public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value >= balanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } }
Transfer tokens from other address Send `_value` tokens to `_to` in behalf of `_from` _from The address of the sender _to The address of the recipient _value the amount to send/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; }
10,484,970
//Address: 0xa1de36ede424207b476c78405122beb08ac48b89 //Contract name: ServiceStation //Balance: 0.0127832 Ether //Verification Date: 3/27/2018 //Transacion Count: 32 // CODE STARTS HERE pragma solidity ^0.4.21; // Fucking kek that you read the source code // Warning this contract has an exit scam. contract GameState{ // Vote timer / Buy in round / Lowest gas round / Close time. uint256[3] RoundTimes = [(5 minutes), (20 minutes), (10 minutes)]; // 5 20 10 uint256[3] NextRound = [1,2,0]; // Round flow order. // Block external calls altering the game mode. // modifier BlockExtern(){ // require(msg.sender==caller); // _; // } uint256 public CurrentGame = 0; /// bool StartedGame = false; uint256 public Timestamp = 0; function Timer() internal view returns (bool){ if (block.timestamp < Timestamp){ // StartedGame = false; return (true); } return false; } // FixTimer is only for immediate start rounds // takes last timer and adds stuff to that function Start() internal { Timestamp = block.timestamp + RoundTimes[CurrentGame]; // StartedGame=true; } function Next(bool StartNow) internal { uint256 NextRoundBuffer = NextRound[CurrentGame]; if (StartNow){ //Start(); // StartedGame = true; Timestamp = Timestamp + RoundTimes[NextRoundBuffer]; } else{ // StartedGame = false; } CurrentGame = NextRoundBuffer; } // function GameState() public { // caller = msg.sender; // } // returns bit number n from uint. //function GetByte(uint256 bt, uint256 n) public returns (uint256){ // return ((bt >> n) & (1)); // } } contract ServiceStation is GameState{ uint256 public Votes = 0; uint256 public constant VotesNecessary = 6; // THIS CANNOT BE 1 uint256 public constant devFee = 500; // 5% address owner; // Fee address is a contract and is supposed to be used for future projects. // You can buy a dividend card here, which gives you 10% of the development fee. // If someone else buys it, the contract enforces you do make profit by transferring // (part of) the cost of the card to you. // It will also pay out all dividends if someone buys the card // A withdraw function is also available to withdraw the dividends up to that point. // The way to lose money with this card is if not enough dev fee enters the contract AND no one buys the card. // You can buy it on https://etherguy.surge.sh (if this site is offline, contact me). (Or check contract address and run it in remix to manually buy.) address constant fee_address = 0x3323075B8D3c471631A004CcC5DAD0EEAbc5B4D1; event NewVote(uint256 AllVotes); event VoteStarted(); event ItemBought(uint256 ItemID, address OldOwner, address NewOwner, uint256 NewPrice, uint256 FlipAmount); event JackpotChange(uint256 HighJP, uint256 LowJP); event OutGassed(bool HighGame, uint256 NewGas, address WhoGassed, address NewGasser); event Paid(address Paid, uint256 Amount); modifier OnlyDev(){ require(msg.sender==owner); _; } modifier OnlyState(uint256 id){ require (CurrentGame == id); _; } // OR relation modifier OnlyStateOR(uint256 id, uint256 id2){ require (CurrentGame == id || CurrentGame == id2); _; } // Thanks to TechnicalRise // Ban contracts modifier NoContract(){ uint size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0); _; } function ServiceStation() public { owner = msg.sender; } // State 0 rules // Simply vote. function Vote() public NoContract OnlyStateOR(0,2) { bool StillOpen; if (CurrentGame == 2){ StillOpen = Timer(); if (StillOpen){ revert(); // cannot vote yet. } else{ Next(false); // start in next lines. } } StillOpen = Timer(); if (!StillOpen){ emit VoteStarted(); Start(); Votes=0; } if ((Votes+1)>= VotesNecessary){ GameStart(); } else{ Votes++; } emit NewVote(Votes); } function DevForceOpen() public NoContract OnlyState(0) OnlyDev { emit NewVote(VotesNecessary); Timestamp = now; // prevent that round immediately ends if votes were long ago. GameStart(); } // State 1 rules // Pyramid scheme, buy in for 10% jackpot. function GameStart() internal OnlyState(0){ RoundNumber++; Votes = 0; // pay latest persons if not yet paid. Withdraw(); Next(true); TotalPot = address(this).balance; } uint256 RoundNumber = 0; uint256 constant MaxItems = 11; // max id, so max items - 1 please here. uint256 constant StartPrice = (0.005 ether); uint256 constant PriceIncrease = 9750; uint256 constant PotPaidTotal = 8000; uint256 constant PotPaidHigh = 9000; uint256 constant PreviousPaid = 6500; uint256 public TotalPot; // This stores if you are in low jackpot, high jackpot // It uses numbers to keep track how much items you have. mapping(address => bool) LowJackpot; mapping(address => uint256) HighJackpot; mapping(address => uint256) CurrentRound; address public LowJackpotHolder; address public HighJackpotHolder; uint256 CurrTimeHigh; uint256 CurrTimeLow; uint256 public LowGasAmount; uint256 public HighGasAmount; struct Item{ address holder; uint256 price; } mapping(uint256 => Item) Market; // read jackpots function GetJackpots() public view returns (uint256, uint256){ uint256 PotPaidRound = (TotalPot * PotPaidTotal)/10000; uint256 HighJP = (PotPaidRound * PotPaidHigh)/10000; uint256 LowJP = (PotPaidRound * (10000 - PotPaidHigh))/10000; return (HighJP, LowJP); } function GetItemInfo(uint256 ID) public view returns (uint256, address){ Item memory targetItem = Market[ID]; return (targetItem.price, targetItem.holder); } function BuyItem(uint256 ID) public payable NoContract OnlyState(1){ require(ID <= MaxItems); bool StillOpen = Timer(); if (!StillOpen){ revert(); //Next(); // move on to next at new timer; //msg.sender.transfer(msg.value); // return amount. //return; // cannot buy } uint256 price = Market[ID].price; if (price == 0){ price = StartPrice; } require(msg.value >= price); // excess big goodbye back to owner. if (msg.value > price){ msg.sender.transfer(msg.value-price); } // fee -> out uint256 Fee = (price * (devFee))/10000; uint256 Left = price - Fee; // send fee to fee address which is a contract. you can buy a dividend card to claim 10% of these funds, see above at "address fee_address" fee_address.transfer(Fee); if (price != StartPrice){ // pay previous. address target = Market[ID].holder; uint256 payment = (price * PreviousPaid)/10000; target.transfer (payment); if (target != msg.sender){ if (HighJackpot[target] >= 1){ // Keep track of how many high jackpot items we own. // Why? Because if someone else buys your thing you might have another card // Which still gives you right to do high jackpot. HighJackpot[target] = HighJackpot[target] - 1; } } //LowJackpotHolder = Market[ID].holder; TotalPot = TotalPot + Left - payment; emit ItemBought(ID, target, msg.sender, (price * (PriceIncrease + 10000))/10000, payment); } else{ // Keep track of total pot because we gotta pay people from this later // since people are paid immediately we cannot read this.balance because this decreases TotalPot = TotalPot + Left; emit ItemBought(ID, address(0x0), msg.sender, (price * (PriceIncrease + 10000))/10000, 0); } uint256 PotPaidRound = (TotalPot * PotPaidTotal)/10000; emit JackpotChange((PotPaidRound * PotPaidHigh)/10000, (PotPaidRound * (10000 - PotPaidHigh))/10000); // activate low pot. you can claim low pot if you are not in the high jackpot . LowJackpot[msg.sender] = true; // Update price price = (price * (PriceIncrease + 10000))/10000; // if (CurrentRound[msg.sender] != RoundNumber){ // New round reset count if (HighJackpot[msg.sender] != 1){ HighJackpot[msg.sender] = 1; } CurrentRound[msg.sender] = RoundNumber; } else{ HighJackpot[msg.sender] = HighJackpot[msg.sender] + 1; } Market[ID].holder = msg.sender; Market[ID].price = price; } // Round 2 least gas war // returns: can play (bool), high jackpot (bool) function GetGameType(address targ) public view returns (bool, bool){ if (CurrentRound[targ] != RoundNumber){ // no buy in, reject playing jackpot game return (false,false); } else{ if (HighJackpot[targ] > 0){ // play high jackpot return (true, true); } else{ if (LowJackpot[targ]){ // play low jackpot return (true, false); } } } // functions should not go here. return (false, false); } // function BurnGas() public NoContract OnlyStateOR(2,1) { bool StillOpen; if (CurrentGame == 1){ StillOpen = Timer(); if (!StillOpen){ Next(true); // move to round 2. immediate start } else{ revert(); // gas burn closed. } } StillOpen = Timer(); if (!StillOpen){ Next(true); Withdraw(); return; } bool CanPlay; bool IsPremium; (CanPlay, IsPremium) = GetGameType(msg.sender); require(CanPlay); uint256 AllPot = (TotalPot * PotPaidTotal)/10000; uint256 PotTarget; uint256 timespent; uint256 payment; if (IsPremium){ PotTarget = (AllPot * PotPaidHigh)/10000; if (HighGasAmount == 0 || tx.gasprice < HighGasAmount){ if (HighGasAmount == 0){ emit OutGassed(true, tx.gasprice, address(0x0), msg.sender); } else{ timespent = now - CurrTimeHigh; payment = (PotTarget * timespent) / RoundTimes[2]; // calculate payment and send HighJackpotHolder.transfer(payment); emit OutGassed(true, tx.gasprice, HighJackpotHolder, msg.sender); emit Paid(HighJackpotHolder, payment); } HighGasAmount = tx.gasprice; CurrTimeHigh = now; HighJackpotHolder = msg.sender; } } else{ PotTarget = (AllPot * (10000 - PotPaidHigh)) / 10000; if (LowGasAmount == 0 || tx.gasprice < LowGasAmount){ if (LowGasAmount == 0){ emit OutGassed(false, tx.gasprice, address(0x0), msg.sender); } else{ timespent = now - CurrTimeLow; payment = (PotTarget * timespent) / RoundTimes[2]; // calculate payment and send LowJackpotHolder.transfer(payment); emit OutGassed(false, tx.gasprice, LowJackpotHolder, msg.sender); emit Paid(LowJackpotHolder, payment); } LowGasAmount = tx.gasprice; CurrTimeLow = now; LowJackpotHolder = msg.sender; } } } function Withdraw() public NoContract OnlyStateOR(0,2){ bool gonext = false; if (CurrentGame == 2){ bool StillOpen; StillOpen = Timer(); if (!StillOpen){ gonext = true; } else{ revert(); // no cheats } } uint256 timespent; uint256 payment; uint256 AllPot = (TotalPot * PotPaidTotal)/10000; uint256 PotTarget; if (LowGasAmount != 0){ PotTarget = (AllPot * (10000 - PotPaidHigh))/10000; timespent = Timestamp - CurrTimeLow; payment = (PotTarget * timespent) / RoundTimes[2]; // calculate payment and send LowJackpotHolder.transfer(payment); emit Paid(LowJackpotHolder, payment); } if (HighGasAmount != 0){ PotTarget = (AllPot * PotPaidHigh)/10000; timespent = Timestamp - CurrTimeHigh; payment = (PotTarget * timespent) / RoundTimes[2]; // calculate payment and send HighJackpotHolder.transfer(payment); emit Paid(HighJackpotHolder, payment); } // reset low gas high gas for next round LowGasAmount = 0; HighGasAmount = 0; // reset market prices. uint8 id; for (id=0; id<MaxItems; id++){ Market[id].price=0; } if (gonext){ Next(true); } } // this is added in case something goes wrong // the contract can be funded if any bugs happen when // trying to transfer eth. function() payable{ } }
this is added in case something goes wrong the contract can be funded if any bugs happen when trying to transfer eth.
function() payable{ }
5,407,332
pragma solidity ^0.4.22; // File: contracts/ERC223/ERC223_receiving_contract.sol /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/ERC223/ERC223.sol /** * @title Reference implementation of the ERC223 standard token. */ contract ERC223 is StandardToken { event Transfer(address indexed from, address indexed to, uint value, bytes data); /** * @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, uint _value) public returns (bool) { bytes memory empty; return transfer(_to, _value, empty); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data Optional metadata. */ function transfer(address _to, uint _value, bytes _data) public returns (bool) { super.transfer(_to, _value); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); } return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { bytes memory empty; return transferFrom(_from, _to, _value, empty); } /** * @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 uint the amount of tokens to be transferred * @param _data Optional metadata. */ function transferFrom(address _from, address _to, uint _value, bytes _data) public returns (bool) { super.transferFrom(_from, _to, _value); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(_from, _value, _data); } Transfer(_from, _to, _value, _data); return true; } function isContract(address _addr) private view returns (bool) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } } // 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/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts/RootsToken.sol contract RootsToken is CappedToken, ERC223 { string constant public name = "ROOTS Token"; string constant public symbol = "ROOTS"; uint constant public decimals = 18; function RootsToken() public CappedToken(1e10 * 1e18) {} function mintlist(address[] _to, uint256[] _amount) onlyOwner canMint public { require(_to.length == _amount.length); for (uint256 i = 0; i < _to.length; i++) { mint(_to[i], _amount[i]); } } }
retrieve the size of the code on target address, this needs assembly
function isContract(address _addr) private view returns (bool) { uint length; assembly { length := extcodesize(_addr) } return (length>0); }
393,674
//Address: 0xda9f43015749056182352e9dc6d3ee0b6293d80a //Contract name: EtherLambosCore //Balance: 0 Ether //Verification Date: 3/11/2018 //Transacion Count: 155 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @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 Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Optional methods used by ServiceStation contract function tuneLambo(uint256 _newattributes, uint256 _tokenId) external; function getLamboAttributes(uint256 _id) external view returns (uint256 attributes); function getLamboModel(uint256 _tokenId) external view returns (uint64 _model); // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /// @title A facet of EtherLamboCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) adapted by Kenny Bania /// @dev ... contract EtherLambosAccessControl { // This facet controls access control for Etherlambos. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the EtherLamboCore constructor. // // - The CFO: The CFO can withdraw funds from EtherLamboCore and its auction contracts. // // - The COO: The COO can release new models for sale. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for EtherLambos. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) adapted by Kenny Bania /// @dev ... contract EtherLambosBase is EtherLambosAccessControl { /*** EVENTS ***/ /// @dev The Build event is fired whenever a new car model is build by the COO event Build(address owner, uint256 lamboId, uint256 attributes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a car /// ownership is assigned, including builds. event Transfer(address from, address to, uint256 tokenId); event Tune(uint256 _newattributes, uint256 _tokenId); /*** DATA TYPES ***/ /// @dev The main EtherLambos struct. Every car in EtherLambos is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Lambo { // sports-car attributes like max speed, weight etc. are stored here. // These attributes can be changed due to tuning/upgrades uint256 attributes; // The timestamp from the block when this car came was constructed. uint64 buildTime; // the Lambo model identifier uint64 model; } // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Lambo struct for all Lambos in existence. The ID /// of each car is actually an index into this array. Note that 0 is invalid index. Lambo[] lambos; /// @dev A mapping from car IDs to the address that owns them. All cars have /// some valid owner address. mapping (uint256 => address) public lamboIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from LamboIDs to an address that has been approved to call /// transferFrom(). Each Lambo can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public lamboIndexToApproved; /// @dev The address of the MarketPlace contract that handles sales of Lambos. This /// same contract handles both peer-to-peer sales as well as new model sales. MarketPlace public marketPlace; ServiceStation public serviceStation; /// @dev Assigns ownership of a specific Lambo to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of lambos is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership lamboIndexToOwner[_tokenId] = _to; // When creating new lambos _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete lamboIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new lambo and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Build event /// and a Transfer event. /// @param _attributes The lambo's attributes. /// @param _owner The inital owner of this car, must be non-zero function _createLambo( uint256 _attributes, address _owner, uint64 _model ) internal returns (uint) { Lambo memory _lambo = Lambo({ attributes: _attributes, buildTime: uint64(now), model:_model }); uint256 newLamboId = lambos.push(_lambo) - 1; // It's probably never going to happen, 4 billion cars is A LOT, but // let's just be 100% sure we never let this happen. require(newLamboId == uint256(uint32(newLamboId))); // emit the build event Build( _owner, newLamboId, _lambo.attributes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newLamboId); return newLamboId; } /// @dev An internal method that tunes an existing lambo. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate a Tune event /// @param _newattributes The lambo's new attributes. /// @param _tokenId The car to be tuned. function _tuneLambo( uint256 _newattributes, uint256 _tokenId ) internal { lambos[_tokenId].attributes=_newattributes; // emit the tune event Tune( _tokenId, _newattributes ); } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { //require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the cars, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// @title The facet of the EtherLambosCore contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) adapted by Cryptoknights /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 contract EtherLambosOwnership is EtherLambosBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "EtherLambos"; string public constant symbol = "EL"; // The contract that will return lambo metadata ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. function setMetadataAddress(address _contractAddress) public onlyCEO { erc721Metadata = ERC721Metadata(_contractAddress); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Lambo. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return lamboIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Lambo. /// @param _claimant the address we are confirming Lambo is approved for. /// @param _tokenId lambo id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return lamboIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Lambos on sale, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { lamboIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Lambos owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Lambo to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// EtherLambos specifically) or your Lambo may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Lambo to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any lambos. require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Marketplace contracts should only take ownership of Lambos // through the allow + transferFrom flow. require(_to != address(marketPlace)); // You can only send your own car. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Lambo via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Lambo that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Lambo owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Lambo to be transfered. /// @param _to The address that should take ownership of the Lambo. Can be any address, /// including the caller. /// @param _tokenId The ID of the Lambo to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any lambos. require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Lambos currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return lambos.length - 1; } /// @notice Returns the address currently assigned ownership of a given Lambo. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = lamboIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Lambo IDs assigned to an address. /// @param _owner The owner whose Lambo we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Lambo array looking for cars belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCars = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all cars have IDs starting at 1 and increasing // sequentially up to the totalCat count. uint256 carId; for (carId = 1; carId <= totalCars; carId++) { if (lamboIndexToOwner[carId] == _owner) { result[resultIndex] = carId; resultIndex++; } } return result; } } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes 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)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the Lambos whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); bytes32[4] memory buffer; uint256 count; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } } /// @title MarketPlace core /// @dev Contains models, variables, and internal methods for the marketplace. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract MarketPlaceBase is Ownable { // Represents an sale on an NFT struct Sale { // Current owner of NFT address seller; // Price (in wei) uint128 price; // Time when sale started // NOTE: 0 if this sale has been concluded uint64 startedAt; } struct Affiliates { address affiliate_address; uint64 commission; uint64 pricecut; } //Affiliates[] affiliates; // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each sale, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; //map the Affiliate Code to the Affiliate mapping (uint256 => Affiliates) codeToAffiliate; // Map from token ID to their corresponding sale. mapping (uint256 => Sale) tokenIdToSale; event SaleCreated(uint256 tokenId, uint256 price); event SaleSuccessful(uint256 tokenId, uint256 price, address buyer); event SaleCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an sale to the list of open sales. Also fires the /// SaleCreated event. /// @param _tokenId The ID of the token to be put on sale. /// @param _sale Sale to add. function _addSale(uint256 _tokenId, Sale _sale) internal { tokenIdToSale[_tokenId] = _sale; SaleCreated( uint256(_tokenId), uint256(_sale.price) ); } /// @dev Cancels a sale unconditionally. function _cancelSale(uint256 _tokenId, address _seller) internal { _removeSale(_tokenId); _transfer(_seller, _tokenId); SaleCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return a sale object that is all zeros.) require(_isOnSale(sale)); // Check that the bid is greater than or equal to the current price uint256 price = sale.price; require(_bidAmount >= price); // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; // The bid is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the Marketplace's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 marketplaceCut = _computeCut(price); uint256 sellerProceeds = price - marketplaceCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! SaleSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes a sale from the list of open sales. /// @param _tokenId - ID of NFT on sale. function _removeSale(uint256 _tokenId) internal { delete tokenIdToSale[_tokenId]; } /// @dev Returns true if the NFT is on sale. /// @param _sale - Sale to check. function _isOnSale(Sale storage _sale) internal view returns (bool) { return (_sale.startedAt > 0); } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the Marketplace constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } function _computeAffiliateCut(uint256 _price,Affiliates affiliate) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the Marketplace constructor). The result of this // function is always guaranteed to be <= _price. return _price * affiliate.commission / 10000; } /// @dev Adds an affiliate to the list. /// @param _code The referall code of the affiliate. /// @param _affiliate Affiliate to add. function _addAffiliate(uint256 _code, Affiliates _affiliate) internal { codeToAffiliate[_code] = _affiliate; } /// @dev Removes a affiliate from the list. /// @param _code - The referall code of the affiliate. function _removeAffiliate(uint256 _code) internal { delete codeToAffiliate[_code]; } //_bidReferral(_tokenId, msg.value); /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidReferral(uint256 _tokenId, uint256 _bidAmount,Affiliates _affiliate) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; //Only Owner of Contract can sell referrals require(sale.seller==owner); // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return a sale object that is all zeros.) require(_isOnSale(sale)); // Check that the bid is greater than or equal to the current price uint256 price = sale.price; //deduce the affiliate pricecut price=price * _affiliate.pricecut / 10000; require(_bidAmount >= price); // Grab a reference to the seller before the sale struct // gets deleted. address seller = sale.seller; address affiliate_address = _affiliate.affiliate_address; // The bid is good! Remove the sale before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the Marketplace's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 affiliateCut = _computeAffiliateCut(price,_affiliate); uint256 sellerProceeds = price - affiliateCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); affiliate_address.transfer(affiliateCut); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! SaleSuccessful(_tokenId, price, msg.sender); return price; } } /** * @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 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() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// @title MarketPlace for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract MarketPlace is Pausable, MarketPlaceBase { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleMarketplaceAddress() call. bool public isMarketplace = true; /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each sale, must be /// between 0-10,000. function MarketPlace(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); //require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } function setNFTAddress(address _nftAddress, uint256 _cut) external onlyOwner { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); //require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work bool res = nftAddress.send(this.balance); } /// @dev Creates and begins a new sale. /// @param _tokenId - ID of token to sale, sender must be owner. /// @param _price - Price of item (in wei) /// @param _seller - Seller, if not the message sender function createSale( uint256 _tokenId, uint256 _price, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_price == uint256(uint128(_price))); //require(_owns(msg.sender, _tokenId)); //_escrow(msg.sender, _tokenId); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Sale memory sale = Sale( _seller, uint128(_price), uint64(now) ); _addSale(_tokenId, sale); } /// @dev Bids on a sale, completing the sale and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Bids on a sale, completing the sale and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bidReferral(uint256 _tokenId,uint256 _code) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails Affiliates storage affiliate = codeToAffiliate[_code]; require(affiliate.affiliate_address!=0&&_code>0); _bidReferral(_tokenId, msg.value,affiliate); _transfer(msg.sender, _tokenId); } /// @dev Cancels an sale that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on sale function cancelSale(uint256 _tokenId) external { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); address seller = sale.seller; require(msg.sender == seller); _cancelSale(_tokenId, seller); } /// @dev Cancels a sale when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on sale to cancel. function cancelSaleWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); _cancelSale(_tokenId, sale.seller); } /// @dev Returns sale info for an NFT on sale. /// @param _tokenId - ID of NFT on sale. function getSale(uint256 _tokenId) external view returns ( address seller, uint256 price, uint256 startedAt ) { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); return ( sale.seller, sale.price, sale.startedAt ); } /// @dev Returns the current price of a sale. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); return sale.price; } /// @dev Creates and begins a new sale. /// @param _code - ID of token to sale, sender must be owner. /// @param _commission - percentage of commission for affiliate /// @param _pricecut - percentage of sell price cut for buyer /// @param _affiliate_address - affiliate address function createAffiliate( uint256 _code, uint64 _commission, uint64 _pricecut, address _affiliate_address ) external onlyOwner { Affiliates memory affiliate = Affiliates( address(_affiliate_address), uint64(_commission), uint64(_pricecut) ); _addAffiliate(_code, affiliate); } /// @dev Returns affiliate info for an affiliate code. /// @param _code - code for an affiliate. function getAffiliate(uint256 _code) external view onlyOwner returns ( address affiliate_address, uint64 commission, uint64 pricecut ) { Affiliates storage affiliate = codeToAffiliate[_code]; return ( affiliate.affiliate_address, affiliate.commission, affiliate.pricecut ); } /// @dev Removes affiliate. /// Only the owner may do this /// @param _code - code for an affiliate. function removeAffiliate(uint256 _code) onlyOwner external { _removeAffiliate(_code); } } /// @title ServiceStationBase core /// @dev Contains models, variables, and internal methods for the ServiceStation. contract ServiceStationBase { // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; struct Tune{ uint256 startChange; uint256 rangeChange; uint256 attChange; bool plusMinus; bool replace; uint128 price; bool active; uint64 model; } Tune[] options; /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Calls the NFT Contract with the tuned attributes function _tune(uint256 _newattributes, uint256 _tokenId) internal { nonFungibleContract.tuneLambo(_newattributes, _tokenId); } function _changeAttributes(uint256 _tokenId,uint256 _optionIndex) internal { //Get model from token uint64 model = nonFungibleContract.getLamboModel(_tokenId); //throw if tune option is not made for model require(options[_optionIndex].model==model); //Get original attributes uint256 attributes = nonFungibleContract.getLamboAttributes(_tokenId); uint256 part=0; //Dissect for options part=(attributes/(10 ** options[_optionIndex].startChange)) % (10 ** options[_optionIndex].rangeChange); //part=1544; //Change attributes & verify //Should attChange be added,subtracted or replaced? if(options[_optionIndex].replace == false) { //change should be added if(options[_optionIndex].plusMinus == false) { //e.g. if range = 4 then value can not be higher then 9999 - overflow check require((part+options[_optionIndex].attChange)<(10**options[_optionIndex].rangeChange)); //add to attributes attributes=attributes+options[_optionIndex].attChange*(10 ** options[_optionIndex].startChange); } else{ //do some subtraction //e.g. value must be greater then 0 require(part>options[_optionIndex].attChange); //substract from attributes attributes-=options[_optionIndex].attChange*(10 ** options[_optionIndex].startChange); } } else { //do some replacing attributes=attributes-part*(10 ** options[_optionIndex].startChange); attributes+=options[_optionIndex].attChange*(10 ** options[_optionIndex].startChange); } //Tune Lambo in NFT contract _tune(uint256(attributes), _tokenId); } } /// @title ServiceStation for non-fungible tokens. contract ServiceStation is Pausable, ServiceStationBase { // @dev Sanity check that allows us to ensure that we are pointing to the right call. bool public isServicestation = true; /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); uint256 public optionCount; mapping (uint64 => uint256) public modelIndexToOptionCount; /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. function ServiceStation(address _nftAddress) public { ERC721 candidateContract = ERC721(_nftAddress); //require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; _newTuneOption(0,0,0,false,false,0,0); } function setNFTAddress(address _nftAddress) external onlyOwner { ERC721 candidateContract = ERC721(_nftAddress); //require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } function newTuneOption( uint32 _startChange, uint32 _rangeChange, uint256 _attChange, bool _plusMinus, bool _replace, uint128 _price, uint64 _model ) external { //Only allow owner to add new options require(msg.sender == owner ); optionCount++; modelIndexToOptionCount[_model]++; _newTuneOption(_startChange,_rangeChange,_attChange,_plusMinus, _replace,_price,_model); } function changeTuneOption( uint32 _startChange, uint32 _rangeChange, uint256 _attChange, bool _plusMinus, bool _replace, uint128 _price, bool _isactive, uint64 _model, uint256 _optionIndex ) external { //Only allow owner to add new options require(msg.sender == owner ); _changeTuneOption(_startChange,_rangeChange,_attChange,_plusMinus, _replace,_price,_isactive,_model,_optionIndex); } function _newTuneOption( uint32 _startChange, uint32 _rangeChange, uint256 _attChange, bool _plusMinus, bool _replace, uint128 _price, uint64 _model ) internal { Tune memory _option = Tune({ startChange: _startChange, rangeChange: _rangeChange, attChange: _attChange, plusMinus: _plusMinus, replace: _replace, price: _price, active: true, model: _model }); options.push(_option); } function _changeTuneOption( uint32 _startChange, uint32 _rangeChange, uint256 _attChange, bool _plusMinus, bool _replace, uint128 _price, bool _isactive, uint64 _model, uint256 _optionIndex ) internal { Tune memory _option = Tune({ startChange: _startChange, rangeChange: _rangeChange, attChange: _attChange, plusMinus: _plusMinus, replace: _replace, price: _price, active: _isactive, model: _model }); options[_optionIndex]=_option; } function disableTuneOption(uint256 index) external { require(msg.sender == owner ); options[index].active=false; } function enableTuneOption(uint256 index) external { require(msg.sender == owner ); options[index].active=true; } function getOption(uint256 _index) external view returns ( uint256 _startChange, uint256 _rangeChange, uint256 _attChange, bool _plusMinus, uint128 _price, bool active, uint64 model ) { //require(options[_index].active); return ( options[_index].startChange, options[_index].rangeChange, options[_index].attChange, options[_index].plusMinus, options[_index].price, options[_index].active, options[_index].model ); } function getOptionCount() external view returns (uint256 _optionCount) { return optionCount; } function tuneLambo(uint256 _tokenId,uint256 _optionIndex) external payable { //Caller needs to own Lambo require(_owns(msg.sender, _tokenId)); //Tuning Option needs to be enabled require(options[_optionIndex].active); //Enough money for tuning to spend? require(msg.value>=options[_optionIndex].price); _changeAttributes(_tokenId,_optionIndex); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work bool res = owner.send(this.balance); } function getOptionsForModel(uint64 _model) external view returns(uint256[] _optionsModel) { //uint256 tokenCount = balanceOf(_owner); //if (tokenCount == 0) { // Return an empty array // return new uint256[](0); //} else { uint256[] memory result = new uint256[](modelIndexToOptionCount[_model]); //uint256 totalCars = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all cars have IDs starting at 0 and increasing // sequentially up to the optionCount count. uint256 optionId; for (optionId = 1; optionId <= optionCount; optionId++) { if (options[optionId].model == _model && options[optionId].active == true) { result[resultIndex] = optionId; resultIndex++; } } return result; // } } } ////No SiringClockAuction needed for Lambos ////No separate modification for SaleContract needed /// @title Handles creating sales for sale of lambos. /// This wrapper of ReverseSale exists only so that users can create /// sales with only one transaction. contract EtherLambosSale is EtherLambosOwnership { // @notice The sale contract variables are defined in EtherLambosBase to allow // us to refer to them in EtherLambosOwnership to prevent accidental transfers. // `saleMarketplace` refers to the auction for p2p sale of cars. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setMarketplaceAddress(address _address) external onlyCEO { MarketPlace candidateContract = MarketPlace(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isMarketplace()); // Set the new contract address marketPlace = candidateContract; } /// @dev Put a lambo up for sale. /// Does some ownership trickery to create auctions in one tx. function createLamboSale( uint256 _carId, uint256 _price ) external whenNotPaused { // Sale contract checks input sizes // If lambo is already on any sale, this will throw // because it will be owned by the sale contract. require(_owns(msg.sender, _carId)); _approve(_carId, marketPlace); // Sale throws if inputs are invalid and clears // transfer after escrowing the lambo. marketPlace.createSale( _carId, _price, msg.sender ); } function bulkCreateLamboSale( uint256 _price, uint256 _tokenIdStart, uint256 _tokenCount ) external onlyCOO { // Sale contract checks input sizes // If lambo is already on any sale, this will throw // because it will be owned by the sale contract. for(uint256 i=0;i<_tokenCount;i++) { require(_owns(msg.sender, _tokenIdStart+i)); _approve(_tokenIdStart+i, marketPlace); // Sale throws if inputs are invalid and clears // transfer after escrowing the lambo. marketPlace.createSale( _tokenIdStart+i, _price, msg.sender ); } } /// @dev Transfers the balance of the marketPlace contract /// to the EtherLambosCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawSaleBalances() external onlyCLevel { marketPlace.withdrawBalance(); } } /// @title all functions related to creating lambos contract EtherLambosBuilding is EtherLambosSale { // Limits the number of cars the contract owner can ever create. //uint256 public constant PROMO_CREATION_LIMIT = 5000; //uint256 public constant GEN0_CREATION_LIMIT = 45000; // Counts the number of cars the contract owner has created. uint256 public lambosBuildCount; /// @dev we can build lambos. Only callable by COO /// @param _attributes the encoded attributes of the lambo to be created, any value is accepted /// @param _owner the future owner of the created lambo. Default to contract COO /// @param _model the model of the created lambo. function createLambo(uint256 _attributes, address _owner, uint64 _model) external onlyCOO { address lamboOwner = _owner; if (lamboOwner == address(0)) { lamboOwner = cooAddress; } //require(promoCreatedCount < PROMO_CREATION_LIMIT); lambosBuildCount++; _createLambo(_attributes, lamboOwner, _model); } function bulkCreateLambo(uint256 _attributes, address _owner, uint64 _model,uint256 count, uint256 startNo) external onlyCOO { address lamboOwner = _owner; uint256 att=_attributes; if (lamboOwner == address(0)) { lamboOwner = cooAddress; } //do some replacing //_attributes=_attributes-part*(10 ** 66); //require(promoCreatedCount < PROMO_CREATION_LIMIT); for(uint256 i=0;i<count;i++) { lambosBuildCount++; att=_attributes+(startNo+i)*(10 ** 66); _createLambo(att, lamboOwner, _model); } } } /// @title all functions related to tuning lambos contract EtherLambosTuning is EtherLambosBuilding { // Counts the number of tunings have been done. uint256 public lambosTuneCount; function setServicestationAddress(address _address) external onlyCEO { ServiceStation candidateContract = ServiceStation(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isServicestation()); // Set the new contract address serviceStation = candidateContract; } /// @dev we can tune lambos. Only callable by ServiceStation contract /// @param _newattributes the new encoded attributes of the lambo to be updated /// @param _tokenId the lambo to be tuned. function tuneLambo(uint256 _newattributes, uint256 _tokenId) external { //Tuning can only be done by the ServiceStation Contract. require( msg.sender == address(serviceStation) ); lambosTuneCount++; _tuneLambo(_newattributes, _tokenId); } function withdrawTuneBalances() external onlyCLevel { serviceStation.withdrawBalance(); } } /// @title EtherLambos: Collectible, tuneable, and super stylish lambos on the Ethereum blockchain. /// @author Cryptoknights code adapted from Axiom Zen (https://www.axiomzen.co) /// @dev The main EtherLambos contract, keeps track of lambos. contract EtherLambosCore is EtherLambosTuning { // This is the main EtherLambos contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle sales. The sales are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // lambo ownership. // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of EtherLambos. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - EtherLambosBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - EtherLambosAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - EtherLambosOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - EtherLambosSale: Here we have the public methods for sales. // // - EtherLambosBuilding: This final facet contains the functionality we use for creating new cars. // // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main EtherLambos smart contract instance. function EtherLambosCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the car 0 _createLambo(uint256(-1), address(0),0); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from the marketPlace contract. /// (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(marketPlace) ); } /// @notice Returns all the relevant information about a specific lambo. /// @param _id The ID of the lambo of interest. function getLambo(uint256 _id) external view returns ( uint256 buildTime, uint256 attributes ) { Lambo storage kit = lambos[_id]; buildTime = uint256(kit.buildTime); attributes = kit.attributes; } /// @notice Returns all the relevant information about a specific lambo. /// @param _id The ID of the lambo of interest. function getLamboAttributes(uint256 _id) external view returns ( uint256 attributes ) { Lambo storage kit = lambos[_id]; attributes = kit.attributes; return attributes; } /// @notice Returns all the relevant information about a specific lambo. /// @param _id The ID of the lambo of interest. function getLamboModel(uint256 _id) external view returns ( uint64 model ) { Lambo storage kit = lambos[_id]; model = kit.model; return model; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(marketPlace != address(0)); require(serviceStation != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { uint256 balance = this.balance; cfoAddress.send(balance); } }
NOTE: verify that a contract is what we expect - https:github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.solL117 Set the new contract address
function setServicestationAddress(address _address) external onlyCEO { ServiceStation candidateContract = ServiceStation(_address); require(candidateContract.isServicestation()); serviceStation = candidateContract; }
6,354,716
contract tickingBomb { struct team { string name; uint lastUpdate; address[] members; uint nbrMembers; } uint public constant DELAY = 60 * 60 * 24; // 24 Hours uint public constant INVEST_AMOUNT = 1000 finney; // 1 ETH uint constant FEE = 3; team public red; team public blue; mapping(address => uint) public balances; address creator; string[] public historyWinner; uint[] public historyRed; uint[] public historyBlue; uint public gameNbr; function tickingBomb() { newRound(); creator = msg.sender; gameNbr = 0; } function helpRed() { uint i; uint amount = msg.value; // Check if Exploded, if so save the previous game // And create a new round checkIfExploded(); // Update the TimeStamp red.lastUpdate = block.timestamp; // Split the incoming money every INVEST_AMOUNT while (amount >= INVEST_AMOUNT) { red.members.push(msg.sender); red.nbrMembers++; amount -= INVEST_AMOUNT; } // If there is still some money in the balance, sent it back if (amount > 0) { msg.sender.send(amount); } } function helpBlue() { uint i; uint amount = msg.value; // Check if Exploded, if so save the previous game // And create a new game checkIfExploded(); // Update the TimeStamp blue.lastUpdate = block.timestamp; // Split the incoming money every 100 finneys while (amount >= INVEST_AMOUNT) { blue.members.push(msg.sender); blue.nbrMembers++; amount -= INVEST_AMOUNT; } // If there is still some money in the balance, sent it back if (amount > 0) { msg.sender.send(amount); } } function checkIfExploded() { if (checkTime()) { newRound(); } } function checkTime() private returns(bool exploded) { uint i; uint lostAmount = 0; uint gainPerMember = 0; uint feeCollected = 0; // If Red and Blue have exploded at the same time, return the amounted invested if (red.lastUpdate == blue.lastUpdate && red.lastUpdate + DELAY < block.timestamp) { for (i = 0; i < red.members.length; i++) { balances[red.members[i]] += INVEST_AMOUNT; } for (i = 0; i < blue.members.length; i++) { balances[blue.members[i]] += INVEST_AMOUNT; } historyWinner.push('Tie between Red and Blue'); historyRed.push(red.nbrMembers); historyBlue.push(blue.nbrMembers); gameNbr++; return true; } // Take the older timestamp if (red.lastUpdate < blue.lastUpdate) { // Check if the Red bomb exploded if (red.lastUpdate + DELAY < block.timestamp) { // Calculate the lost amount by the red team // Number of Red member * Invested amount per user * feeCollected += (red.nbrMembers * INVEST_AMOUNT * FEE / 100); balances[creator] += feeCollected; lostAmount = (red.nbrMembers * INVEST_AMOUNT) - feeCollected; gainPerMember = lostAmount / blue.nbrMembers; for (i = 0; i < blue.members.length; i++) { balances[blue.members[i]] += (INVEST_AMOUNT + gainPerMember); } historyWinner.push('Red'); historyRed.push(red.nbrMembers); historyBlue.push(blue.nbrMembers); gameNbr++; return true; } return false; } else { // Check if the Blue bomb exploded if (blue.lastUpdate + DELAY < block.timestamp) { // Calculate the lost amount by the red team // Number of Red member * Invested amount per user * feeCollected += (blue.nbrMembers * INVEST_AMOUNT * FEE / 100); balances[creator] += feeCollected; lostAmount = (blue.nbrMembers * INVEST_AMOUNT) - feeCollected; gainPerMember = lostAmount / red.nbrMembers; for (i = 0; i < red.members.length; i++) { balances[red.members[i]] += (INVEST_AMOUNT + gainPerMember); } historyWinner.push('Blue'); historyRed.push(red.nbrMembers); historyBlue.push(blue.nbrMembers); gameNbr++; return true; } return false; } } function newRound() private { red.name = "Red team"; blue.name = "Blue team"; red.lastUpdate = block.timestamp; blue.lastUpdate = block.timestamp; red.nbrMembers = 0; blue.nbrMembers = 0; red.members = new address[](0); blue.members = new address[](0); } function() { // Help the oldest timestamp (going to explode first) if (red.lastUpdate < blue.lastUpdate) { helpRed(); } else { helpBlue(); } } function collectBalance() { msg.sender.send(balances[msg.sender]); balances[msg.sender] = 0; } // Allow the creator to send their balances to the players function sendBalance(address player) { if (msg.sender == creator) { player.send(balances[player]); } } function newOwner(address newOwner) { if (msg.sender == creator) { creator = newOwner; } } }
If Red and Blue have exploded at the same time, return the amounted invested Take the older timestamp Check if the Red bomb exploded Calculate the lost amount by the red team Number of Red member Invested amount per user Check if the Blue bomb exploded Calculate the lost amount by the red team Number of Red member Invested amount per user
function checkTime() private returns(bool exploded) { uint i; uint lostAmount = 0; uint gainPerMember = 0; uint feeCollected = 0; if (red.lastUpdate == blue.lastUpdate && red.lastUpdate + DELAY < block.timestamp) { for (i = 0; i < red.members.length; i++) { balances[red.members[i]] += INVEST_AMOUNT; } for (i = 0; i < blue.members.length; i++) { balances[blue.members[i]] += INVEST_AMOUNT; } historyWinner.push('Tie between Red and Blue'); historyRed.push(red.nbrMembers); historyBlue.push(blue.nbrMembers); gameNbr++; return true; } if (red.lastUpdate < blue.lastUpdate) { if (red.lastUpdate + DELAY < block.timestamp) { feeCollected += (red.nbrMembers * INVEST_AMOUNT * FEE / 100); balances[creator] += feeCollected; lostAmount = (red.nbrMembers * INVEST_AMOUNT) - feeCollected; gainPerMember = lostAmount / blue.nbrMembers; for (i = 0; i < blue.members.length; i++) { balances[blue.members[i]] += (INVEST_AMOUNT + gainPerMember); } historyWinner.push('Red'); historyRed.push(red.nbrMembers); historyBlue.push(blue.nbrMembers); gameNbr++; return true; } return false; if (blue.lastUpdate + DELAY < block.timestamp) { feeCollected += (blue.nbrMembers * INVEST_AMOUNT * FEE / 100); balances[creator] += feeCollected; lostAmount = (blue.nbrMembers * INVEST_AMOUNT) - feeCollected; gainPerMember = lostAmount / red.nbrMembers; for (i = 0; i < red.members.length; i++) { balances[red.members[i]] += (INVEST_AMOUNT + gainPerMember); } historyWinner.push('Blue'); historyRed.push(red.nbrMembers); historyBlue.push(blue.nbrMembers); gameNbr++; return true; } return false; } }
923,445
pragma solidity 0.5.17; import "./MToken.sol"; import "./MomaPool.sol"; // unused currently import "./Governance/Moma.sol"; import "./MomaFactoryInterface.sol"; contract MomaFarming is ExponentialNoError { address public admin; Moma public moma; MomaFactoryInterface public factory; bool public constant isMomaFarming = true; /// @notice The initial moma index for a market uint public constant momaInitialIndex = 1e36; uint public momaSpeed; uint public momaTotalWeight; struct MarketState { /// @notice Whether is MOMA market, used to avoid add to momaMarkets again bool isMomaMarket; /// @notice The market's MOMA weight, times of 1 uint weight; /// @notice The market's block number that the supplyIndex was last updated at uint supplyBlock; /// @notice The market's block number that the borrowIndex was last updated at uint borrowBlock; /// @notice The market's last updated supplyIndex uint supplyIndex; /// @notice The market's last updated borrowIndex uint borrowIndex; /// @notice The market's MOMA supply index of each supplier as of the last time they accrued MOMA mapping(address => uint) supplierIndex; /// @notice The market's MOMA borrow index of each borrower as of the last time they accrued MOMA mapping(address => uint) borrowerIndex; } /// @notice Each MOMA pool's each momaMarket's MarketState mapping(address => mapping(address => MarketState)) public marketStates; /// @notice Each MOMA pool's momaMarkets list mapping(address => MToken[]) public momaMarkets; /// @notice Whether is MOMA lending pool mapping(address => bool) public isMomaLendingPool; /// @notice Whether is MOMA pool, used to avoid add to momaPools again mapping(address => bool) public isMomaPool; /// @notice A list of all MOMA pools MomaPool[] public momaPools; /// @notice The MOMA accrued but not yet transferred to each user mapping(address => uint) public momaAccrued; /// @notice Emitted when MOMA is distributed to a supplier event DistributedSupplier(address indexed pool, MToken indexed mToken, address indexed supplier, uint momaDelta, uint marketSupplyIndex); /// @notice Emitted when MOMA is distributed to a borrower event DistributedBorrower(address indexed pool, MToken indexed mToken, address indexed borrower, uint momaDelta, uint marketBorrowIndex); /// @notice Emitted when MOMA is claimed by user event MomaClaimed(address user, uint accrued, uint claimed, uint notClaimed); /// @notice Emitted when admin is changed by admin event NewAdmin(address oldAdmin, address newAdmin); /// @notice Emitted when factory is changed by admin event NewFactory(MomaFactoryInterface oldFactory, MomaFactoryInterface newFactory); /// @notice Emitted when momaSpeed is changed by admin event NewMomaSpeed(uint oldMomaSpeed, uint newMomaSpeed); /// @notice Emitted when a new MOMA weight is changed by admin event NewMarketWeight(address indexed pool, MToken indexed mToken, uint oldWeight, uint newWeight); /// @notice Emitted when a new MOMA total weight is updated event NewTotalWeight(uint oldTotalWeight, uint newTotalWeight); /// @notice Emitted when a new MOMA market is added to momaMarkets event NewMomaMarket(address indexed pool, MToken indexed mToken); /// @notice Emitted when a new MOMA pool is added to momaPools event NewMomaPool(address indexed pool); /// @notice Emitted when MOMA is granted by admin event MomaGranted(address recipient, uint amount); constructor (Moma _moma, MomaFactoryInterface _factory) public { admin = msg.sender; moma = _moma; factory = _factory; } /*** Internal Functions ***/ /** * @notice Calculate the new MOMA supply index and block of this market * @dev Non-moma market will return (0, blockNumber). To avoid revert: momaTotalWeight > 0 * @param pool The pool whose supply index to calculate * @param mToken The market whose supply index to calculate * @return (new index, new block) */ function newMarketSupplyStateInternal(address pool, MToken mToken) internal view returns (uint, uint) { MarketState storage state = marketStates[pool][address(mToken)]; uint _index = state.supplyIndex; uint _block = state.supplyBlock; uint blockNumber = getBlockNumber(); // Non-moma market's weight is always 0, will only update block if (blockNumber > _block) { uint speed = div_(mul_(momaSpeed, state.weight), momaTotalWeight); uint deltaBlocks = sub_(blockNumber, _block); uint _momaAccrued = mul_(deltaBlocks, speed); uint supplyTokens = mToken.totalSupply(); Double memory ratio = supplyTokens > 0 ? fraction(_momaAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: _index}), ratio); _index = index.mantissa; _block = blockNumber; } return (_index, _block); } /** * @notice Accrue MOMA to the market by updating the supply state * @dev To avoid revert: no over/underflow * @param pool The pool whose supply state to update * @param mToken The market whose supply state to update */ function updateMarketSupplyStateInternal(address pool, MToken mToken) internal { MarketState storage state = marketStates[pool][address(mToken)]; // Non-moma market's weight will always be 0, 0 weight moma market will also update nothing if (state.weight > 0) { // momaTotalWeight > 0 (uint _index, uint _block) = newMarketSupplyStateInternal(pool, mToken); state.supplyIndex = _index; state.supplyBlock = _block; } } /** * @notice Calculate the new MOMA borrow index and block of this market * @dev Non-moma market will return (0, blockNumber). To avoid revert: momaTotalWeight > 0, marketBorrowIndex > 0 * @param pool The pool whose borrow index to calculate * @param mToken The market whose borrow index to calculate * @param marketBorrowIndex The market borrow index * @return (new index, new block) */ function newMarketBorrowStateInternal(address pool, MToken mToken, uint marketBorrowIndex) internal view returns (uint, uint) { MarketState storage state = marketStates[pool][address(mToken)]; uint _index = state.borrowIndex; uint _block = state.borrowBlock; uint blockNumber = getBlockNumber(); // Non-moma market's weight is always 0, will only update block if (blockNumber > _block) { uint speed = div_(mul_(momaSpeed, state.weight), momaTotalWeight); uint deltaBlocks = sub_(blockNumber, _block); uint _momaAccrued = mul_(deltaBlocks, speed); uint borrowAmount = div_(mToken.totalBorrows(), Exp({mantissa: marketBorrowIndex})); Double memory ratio = borrowAmount > 0 ? fraction(_momaAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: _index}), ratio); _index = index.mantissa; _block = blockNumber; } return (_index, _block); } /** * @notice Accrue MOMA to the market by updating the borrow state * @dev To avoid revert: no over/underflow * @param pool The pool whose borrow state to update * @param mToken The market whose borrow state to update * @param marketBorrowIndex The market borrow index */ function updateMarketBorrowStateInternal(address pool, MToken mToken, uint marketBorrowIndex) internal { if (isMomaLendingPool[pool] == true) { MarketState storage state = marketStates[pool][address(mToken)]; // Non-moma market's weight will always be 0, 0 weight moma market will also update nothing if (state.weight > 0 && marketBorrowIndex > 0) { // momaTotalWeight > 0 (uint _index, uint _block) = newMarketBorrowStateInternal(pool, mToken, marketBorrowIndex); state.borrowIndex = _index; state.borrowBlock = _block; } } } /** * @notice Calculate MOMA accrued by a supplier * @dev To avoid revert: no over/underflow * @param pool The pool in which the supplier is interacting * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute token to * @param supplyIndex The MOMA supply index of this market in Double type * @return (new supplierAccrued, new supplierDelta) */ function newSupplierMomaInternal(address pool, MToken mToken, address supplier, Double memory supplyIndex) internal view returns (uint, uint) { Double memory supplierIndex = Double({mantissa: marketStates[pool][address(mToken)].supplierIndex[supplier]}); uint _supplierAccrued = momaAccrued[supplier]; uint _supplierDelta = 0; // supply before set moma market can still get rewards start from set block if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = momaInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = mToken.balanceOf(supplier); _supplierDelta = mul_(supplierTokens, deltaIndex); _supplierAccrued = add_(_supplierAccrued, _supplierDelta); return (_supplierAccrued, _supplierDelta); } /** * @notice Distribute MOMA accrued by a supplier * @dev To avoid revert: no over/underflow * @param pool The pool in which the supplier is interacting * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOMA to */ function distributeSupplierMomaInternal(address pool, MToken mToken, address supplier) internal { MarketState storage state = marketStates[pool][address(mToken)]; if (state.supplyIndex > state.supplierIndex[supplier]) { Double memory supplyIndex = Double({mantissa: state.supplyIndex}); (uint _supplierAccrued, uint _supplierDelta) = newSupplierMomaInternal(pool, mToken, supplier, supplyIndex); state.supplierIndex[supplier] = supplyIndex.mantissa; momaAccrued[supplier] = _supplierAccrued; emit DistributedSupplier(pool, mToken, supplier, _supplierDelta, supplyIndex.mantissa); } } /** * @notice Calculate MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol * @dev To avoid revert: marketBorrowIndex > 0 * @param pool The pool in which the borrower is interacting * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOMA to * @param marketBorrowIndex The market borrow index * @param borrowIndex The MOMA borrow index of this market in Double type * @return (new borrowerAccrued, new borrowerDelta) */ function newBorrowerMomaInternal(address pool, MToken mToken, address borrower, uint marketBorrowIndex, Double memory borrowIndex) internal view returns (uint, uint) { Double memory borrowerIndex = Double({mantissa: marketStates[pool][address(mToken)].borrowerIndex[borrower]}); uint _borrowerAccrued = momaAccrued[borrower]; uint _borrowerDelta = 0; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(mToken.borrowBalanceStored(borrower), Exp({mantissa: marketBorrowIndex})); _borrowerDelta = mul_(borrowerAmount, deltaIndex); _borrowerAccrued = add_(_borrowerAccrued, _borrowerDelta); } return (_borrowerAccrued, _borrowerDelta); } /** * @notice Distribute MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol * @dev To avoid revert: no over/underflow * @param pool The pool in which the borrower is interacting * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOMA to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerMomaInternal(address pool, MToken mToken, address borrower, uint marketBorrowIndex) internal { if (isMomaLendingPool[pool] == true) { MarketState storage state = marketStates[pool][address(mToken)]; if (state.borrowIndex > state.borrowerIndex[borrower] && marketBorrowIndex > 0) { Double memory borrowIndex = Double({mantissa: state.borrowIndex}); (uint _borrowerAccrued, uint _borrowerDelta) = newBorrowerMomaInternal(pool, mToken, borrower, marketBorrowIndex, borrowIndex); state.borrowerIndex[borrower] = borrowIndex.mantissa; momaAccrued[borrower] = _borrowerAccrued; emit DistributedBorrower(pool, mToken, borrower, _borrowerDelta, borrowIndex.mantissa); } } } /** * @notice Transfer MOMA to the user * @dev Note: If there is not enough MOMA, will do not perform the transfer * @param user The address of the user to transfer MOMA to * @param amount The amount of token to (possibly) transfer * @return The amount of token which was NOT transferred to the user */ function grantMomaInternal(address user, uint amount) internal returns (uint) { uint remaining = moma.balanceOf(address(this)); if (amount > 0 && amount <= remaining) { moma.transfer(user, amount); return 0; } return amount; } /** * @notice Claim all the MOMA have been distributed to user * @param user The address to claim MOMA for */ function claim(address user) internal { uint accrued = momaAccrued[user]; uint notClaimed = grantMomaInternal(user, accrued); momaAccrued[user] = notClaimed; uint claimed = sub_(accrued, notClaimed); emit MomaClaimed(user, accrued, claimed, notClaimed); } /** * @notice Distribute all the MOMA accrued to user in the specified markets of specified pool * @param user The address to distribute MOMA for * @param pool The moma pool to distribute MOMA in * @param mTokens The list of markets to distribute MOMA in * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function distribute(address user, address pool, MToken[] memory mTokens, bool suppliers, bool borrowers) internal { for (uint i = 0; i < mTokens.length; i++) { MToken mToken = mTokens[i]; if (suppliers == true) { updateMarketSupplyStateInternal(pool, mToken); distributeSupplierMomaInternal(pool, mToken, user); } if (borrowers == true && isMomaLendingPool[pool] == true) { uint borrowIndex = mToken.borrowIndex(); updateMarketBorrowStateInternal(pool, mToken, borrowIndex); distributeBorrowerMomaInternal(pool, mToken, user, borrowIndex); } } } /** * @notice Distribute all the MOMA accrued to user in all markets of specified pools * @param user The address to distribute MOMA for * @param pools The list of moma pools to distribute MOMA * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function distribute(address user, MomaPool[] memory pools, bool suppliers, bool borrowers) internal { for (uint i = 0; i < pools.length; i++) { address pool = address(pools[i]); distribute(user, pool, momaMarkets[pool], suppliers, borrowers); } } /*** Factory Functions ***/ /** * @notice Update pool market's borrowBlock when it upgrades to lending pool in factory * @dev Note: can only call once by factory * @param pool The pool to upgrade */ function upgradeLendingPool(address pool) external { require(msg.sender == address(factory), 'MomaFarming: not factory'); require(isMomaLendingPool[pool] == false, 'MomaFarming: can only upgrade once'); uint blockNumber = getBlockNumber(); MToken[] memory mTokens = momaMarkets[pool]; for (uint i = 0; i < mTokens.length; i++) { MarketState storage state = marketStates[pool][address(mTokens[i])]; state.borrowBlock = blockNumber; // if state.weight > 0 ? } isMomaLendingPool[pool] = true; } /*** Called Functions ***/ /** * @notice Accrue MOMA to the market by updating the supply state * @param mToken The market whose supply state to update */ function updateMarketSupplyState(address mToken) external { require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool'); updateMarketSupplyStateInternal(msg.sender, MToken(mToken)); } /** * @notice Accrue MOMA to the market by updating the borrow state * @param mToken The market whose borrow state to update * @param marketBorrowIndex The market borrow index */ function updateMarketBorrowState(address mToken, uint marketBorrowIndex) external { require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool'); updateMarketBorrowStateInternal(msg.sender, MToken(mToken), marketBorrowIndex); } /** * @notice Distribute MOMA accrued by a supplier * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOMA to */ function distributeSupplierMoma(address mToken, address supplier) external { require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool'); distributeSupplierMomaInternal(msg.sender, MToken(mToken), supplier); } /** * @notice Distribute MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOMA to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) external { require(factory.isMomaPool(msg.sender), 'MomaFarming: not moma pool'); distributeBorrowerMomaInternal(msg.sender, MToken(mToken), borrower, marketBorrowIndex); } /** * @notice Distribute all the MOMA accrued to user in specified markets of specified pool and claim * @param pool The moma pool to distribute MOMA in * @param mTokens The list of markets to distribute MOMA in * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function dclaim(address pool, MToken[] memory mTokens, bool suppliers, bool borrowers) public { distribute(msg.sender, pool, mTokens, suppliers, borrowers); claim(msg.sender); } /** * @notice Distribute all the MOMA accrued to user in all markets of specified pools and claim * @param pools The list of moma pools to distribute and claim MOMA * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function dclaim(MomaPool[] memory pools, bool suppliers, bool borrowers) public { distribute(msg.sender, pools, suppliers, borrowers); claim(msg.sender); } /** * @notice Distribute all the MOMA accrued to user in all markets of all pools and claim * @param suppliers Whether or not to distribute MOMA earned by supplying * @param borrowers Whether or not to distribute MOMA earned by borrowing */ function dclaim(bool suppliers, bool borrowers) public { distribute(msg.sender, momaPools, suppliers, borrowers); claim(msg.sender); } /** * @notice Claim all the MOMA have been distributed to user */ function claim() public { claim(msg.sender); } /*** View Functions ***/ /** * @notice Calculate the speed of a moma market * @param pool The moma pool to calculate speed * @param mToken The moma market to calculate speed * @return The mama market speed */ function getMarketSpeed(address pool, address mToken) public view returns (uint) { if (momaTotalWeight == 0) return 0; return div_(mul_(momaSpeed, marketStates[pool][mToken].weight), momaTotalWeight); } /** * @notice Return all of the moma pools * @dev The automatic getter may be used to access an individual pool * @return The list of pool addresses */ function getAllMomaPools() public view returns (MomaPool[] memory) { return momaPools; } /** * @notice Return the total number of moma pools * @return The number of mama pools */ function getMomaPoolNum() public view returns (uint) { return momaPools.length; } /** * @notice Return all of the moma markets of the specified pool * @dev The automatic getter may be used to access an individual market * @param pool The moma pool to get moma markets * @return The list of market addresses */ function getMomaMarkets(address pool) public view returns (MToken[] memory) { return momaMarkets[pool]; } /** * @notice Return the total number of moma markets of all pools * @return The number of total mama markets */ function getMomaMarketNum() public view returns (uint num) { for (uint i = 0; i < momaPools.length; i++) { num += momaMarkets[address(momaPools[i])].length; } } /** * @notice Weather this is a moma market * @param pool The moma pool of this market * @param mToken The moma market to ask * @return true or false */ function isMomaMarket(address pool, address mToken) public view returns (bool) { return marketStates[pool][mToken].isMomaMarket; } function isLendingPool(address pool) public view returns (bool) { return factory.isLendingPool(pool); } /** * @notice Calculate undistributed MOMA accrued by the user in specified market of specified pool * @param user The address to calculate MOMA for * @param pool The moma pool to calculate MOMA * @param mToken The market to calculate MOMA * @param suppliers Whether or not to calculate MOMA earned by supplying * @param borrowers Whether or not to calculate MOMA earned by borrowing * @return The amount of undistributed MOMA of this user */ function undistributed(address user, address pool, MToken mToken, bool suppliers, bool borrowers) public view returns (uint) { uint accrued; uint _index; MarketState storage state = marketStates[pool][address(mToken)]; if (suppliers == true) { if (state.weight > 0) { // momaTotalWeight > 0 (_index, ) = newMarketSupplyStateInternal(pool, mToken); } else { _index = state.supplyIndex; } if (_index > state.supplierIndex[user]) { (, accrued) = newSupplierMomaInternal(pool, mToken, user, Double({mantissa: _index})); } } if (borrowers == true && isMomaLendingPool[pool] == true) { uint marketBorrowIndex = mToken.borrowIndex(); if (marketBorrowIndex > 0) { if (state.weight > 0) { // momaTotalWeight > 0 (_index, ) = newMarketBorrowStateInternal(pool, mToken, marketBorrowIndex); } else { _index = state.borrowIndex; } if (_index > state.borrowerIndex[user]) { (, uint _borrowerDelta) = newBorrowerMomaInternal(pool, mToken, user, marketBorrowIndex, Double({mantissa: _index})); accrued = add_(accrued, _borrowerDelta); } } } return accrued; } /** * @notice Calculate undistributed MOMA accrued by the user in all markets of specified pool * @param user The address to calculate MOMA for * @param pool The moma pool to calculate MOMA * @param suppliers Whether or not to calculate MOMA earned by supplying * @param borrowers Whether or not to calculate MOMA earned by borrowing * @return The amount of undistributed MOMA of this user in each market */ function undistributed(address user, address pool, bool suppliers, bool borrowers) public view returns (uint[] memory) { MToken[] memory mTokens = momaMarkets[pool]; uint[] memory accrued = new uint[](mTokens.length); for (uint i = 0; i < mTokens.length; i++) { accrued[i] = undistributed(user, pool, mTokens[i], suppliers, borrowers); } return accrued; } /*** Admin Functions ***/ /** * @notice Set the new admin address * @param newAdmin The new admin address */ function _setAdmin(address newAdmin) external { require(msg.sender == admin && newAdmin != address(0), 'MomaFarming: admin check'); address oldAdmin = admin; admin = newAdmin; emit NewAdmin(oldAdmin, newAdmin); } /** * @notice Set the new factory contract * @param newFactory The new factory contract address */ function _setFactory(MomaFactoryInterface newFactory) external { require(msg.sender == admin && address(newFactory) != address(0), 'MomaFarming: admin check'); require(newFactory.isMomaFactory(), 'MomaFarming: not moma factory'); MomaFactoryInterface oldFactory = factory; factory = newFactory; emit NewFactory(oldFactory, newFactory); } /** * @notice Update state for all MOMA markets of all pools * @dev Note: Be careful of gas spending! */ function updateAllMomaMarkets() public { for (uint i = 0; i < momaPools.length; i++) { address pool = address(momaPools[i]); MToken[] memory mTokens = momaMarkets[pool]; for (uint j = 0; j < mTokens.length; j++) { MToken mToken = mTokens[j]; updateMarketSupplyStateInternal(pool, mToken); if (isMomaLendingPool[pool] == true) { uint borrowIndex = mToken.borrowIndex(); updateMarketBorrowStateInternal(pool, mToken, borrowIndex); } } } } /** * @notice Set the new momaSpeed for all MOMA markets of all pools * @dev Note: can call at any time, but must update state of all moma markets first * @param newMomaSpeed The new momaSpeed */ function _setMomaSpeed(uint newMomaSpeed) public { require(msg.sender == admin, 'MomaFarming: admin check'); // Update state for all MOMA markets of all pools updateAllMomaMarkets(); uint oldMomaSpeed = momaSpeed; momaSpeed = newMomaSpeed; emit NewMomaSpeed(oldMomaSpeed, newMomaSpeed); } /** * @notice Set MOMA markets' weight, will also mark as MOMA market in the first time * @dev Note: can call at any time, but must update state of all moma markets first * @param pool The address of the pool * @param mTokens The markets to set weigh * @param newWeights The new weights, 0 means no new MOMA farm */ function _setMarketsWeight(address payable pool, MToken[] memory mTokens, uint[] memory newWeights) public { require(msg.sender == admin, 'MomaFarming: admin check'); require(factory.isMomaPool(pool), 'MomaFarming: not moma pool'); require(mTokens.length == newWeights.length, "MomaFarming: param length dismatch"); // Update state for all MOMA markets of all pools updateAllMomaMarkets(); uint oldWeightTotal; uint newWeightTotal; uint blockNumber = getBlockNumber(); // Update state for all MOMA markets to be setted for (uint i = 0; i < mTokens.length; i++) { MToken mToken = mTokens[i]; MarketState storage state = marketStates[pool][address(mToken)]; // add this market to momaMarkets if first set if (!state.isMomaMarket) { (bool isListed, ) = MomaMasterV1Storage(pool).markets(address(mToken)); require(isListed == true, "market is not listed"); state.isMomaMarket = true; momaMarkets[pool].push(mToken); emit NewMomaMarket(pool, mToken); // set initial index of this market state.supplyIndex = momaInitialIndex; state.borrowIndex = momaInitialIndex; } uint oldWeight = state.weight; oldWeightTotal = add_(oldWeightTotal, oldWeight); newWeightTotal = add_(newWeightTotal, newWeights[i]); // update weight and block of this market state.weight = newWeights[i]; state.supplyBlock = blockNumber; state.borrowBlock = blockNumber; emit NewMarketWeight(pool, mToken, oldWeight, newWeights[i]); } uint oldMomaTotalWeight = momaTotalWeight; // update momaTotalWeight momaTotalWeight = add_(sub_(momaTotalWeight, oldWeightTotal), newWeightTotal); emit NewTotalWeight(oldMomaTotalWeight, momaTotalWeight); // add this pool to momaPools if first set if (!isMomaPool[pool]) { isMomaPool[pool] = true; momaPools.push(MomaPool(pool)); emit NewMomaPool(pool); // mark to lending pool if (isLendingPool(pool)) isMomaLendingPool[pool] = true; } } /** * @notice Transfer MOMA to the recipient * @dev Note: If there is not enough MOMA, we do not perform the transfer * @param recipient The address of the recipient to transfer MOMA to * @param amount The amount of MOMA to (possibly) transfer */ function _grantMoma(address recipient, uint amount) public { require(msg.sender == admin, 'MomaFarming: only admin can grant token'); uint notTransfered = grantMomaInternal(recipient, amount); require(notTransfered == 0, 'MomaFarming: insufficient MOMA for grant'); emit MomaGranted(recipient, amount); } function getBlockNumber() public view returns (uint) { return block.number; } }
Update state for all MOMA markets of all pools Note: Be careful of gas spending!/
function updateAllMomaMarkets() public { for (uint i = 0; i < momaPools.length; i++) { address pool = address(momaPools[i]); MToken[] memory mTokens = momaMarkets[pool]; for (uint j = 0; j < mTokens.length; j++) { MToken mToken = mTokens[j]; updateMarketSupplyStateInternal(pool, mToken); if (isMomaLendingPool[pool] == true) { uint borrowIndex = mToken.borrowIndex(); updateMarketBorrowStateInternal(pool, mToken, borrowIndex); } } } for (uint i = 0; i < momaPools.length; i++) { address pool = address(momaPools[i]); MToken[] memory mTokens = momaMarkets[pool]; for (uint j = 0; j < mTokens.length; j++) { MToken mToken = mTokens[j]; updateMarketSupplyStateInternal(pool, mToken); if (isMomaLendingPool[pool] == true) { uint borrowIndex = mToken.borrowIndex(); updateMarketBorrowStateInternal(pool, mToken, borrowIndex); } } } for (uint i = 0; i < momaPools.length; i++) { address pool = address(momaPools[i]); MToken[] memory mTokens = momaMarkets[pool]; for (uint j = 0; j < mTokens.length; j++) { MToken mToken = mTokens[j]; updateMarketSupplyStateInternal(pool, mToken); if (isMomaLendingPool[pool] == true) { uint borrowIndex = mToken.borrowIndex(); updateMarketBorrowStateInternal(pool, mToken, borrowIndex); } } } }
12,691,541
./full_match/42/0x89cCda5C57A2D4736fF538d07897a0385b6D3278/sources/Users/apple/Documents/yai-protocol-private/contracts/vaults/orai_vault.sol
function setStrategy(address _strategy) external; hard work should be callable only by the controller (by the hard worker) or by governance
interface IVault { function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256); function doHardWork() external; function rebalance() external; }
16,204,912
./full_match/1/0x4670AE81C6A26586D8Cc7e1012A41e0cD8662959/sources/contracts/TagEscrow.sol
Transfers the right to collect the fee. This checks what side the NFT represents escrowId The Escrow selected nftTokenId The NFT token newOwner The address of the new owner/
function transferRightToCollect(uint256 escrowId, uint256 nftTokenId, address newOwner) external nftContractOnly onlyOpenCase(escrowId) { addEscrowIdToAddress(escrowId, newOwner); address oldOwner; EscrowVault memory escrow = escrows[escrowId]; if (escrow.nftA != 0 && escrow.nftA == nftTokenId) { oldOwner = escrows[escrowId].partyA; escrows[escrowId].partyA = newOwner; oldOwner = escrows[escrowId].partyA; escrows[escrowId].partyB = newOwner; } uint l = walletEscrows[oldOwner].escrowIds.length; uint256[] memory newWalletEscrows = new uint256[](l - 1); uint j = 0; for(uint i = 0; i < l; i++) { if (walletEscrows[oldOwner].escrowIds[i] != escrowId) { newWalletEscrows[j] = walletEscrows[oldOwner].escrowIds[i]; j += 1; } } walletEscrows[oldOwner] = IdContainer(newWalletEscrows); }
16,444,619
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.10; import "../../interfaces/IIdleCDOStrategy.sol"; import "../../interfaces/IMAsset.sol"; import "../../interfaces/ISavingsContractV2.sol"; import "../../interfaces/IERC20Detailed.sol"; import "../../interfaces/IVault.sol"; import "../../interfaces/IUniswapV2Router02.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; /// @author IdleHusbandry. /// @title IdleMStableStrategy /// @notice IIdleCDOStrategy to deploy funds in Idle Finance /// @dev This contract should not have any funds at the end of each tx. contract IdleMStableStrategy is Initializable, OwnableUpgradeable, ERC20Upgradeable, ReentrancyGuardUpgradeable, IIdleCDOStrategy { using SafeERC20Upgradeable for IERC20Detailed; /// @notice underlying token address (eg mUSD) address public override token; /// @notice address of the strategy used, in this case imUSD address public override strategyToken; /// @notice decimals of the underlying asset uint256 public override tokenDecimals; /// @notice one underlying token uint256 public override oneToken; /// @notice idleToken contract ISavingsContractV2 public imUSD; /// @notice underlying ERC20 token contract IERC20Detailed public underlyingToken; /* ------------Extra declarations ---------------- */ /// @notice address of the governance token. (Here META) address public govToken; /// @notice vault IVault public vault; /// @notice address of the IdleCDO address public idleCDO; /// @notice uniswap router path that should be used to swap the tokens address[] public uniswapRouterPath; /// @notice interface derived from uniswap router IUniswapV2Router02 public uniswapV2Router02; /// @notice amount last indexed for calculating APR uint256 public lastIndexAmount; /// @notice time when last deposit/redeem was made, used for calculating the APR uint256 public lastIndexedTime; /// @notice one year, used to calculate the APR uint256 public constant YEAR = 365 days; /// @notice round for which the last reward is claimed uint256 public rewardLastRound; /// @notice total imUSD tokens staked uint256 public totalLpTokensStaked; /// @notice total imUSD tokens locked uint256 public totalLpTokensLocked; /// @notice harvested imUSD tokens release delay uint256 public releaseBlocksPeriod; /// @notice latest harvest uint256 public latestHarvestBlock; /// @custom:oz-upgrades-unsafe-allow constructor constructor() { token = address(1); } /// @notice Can be called only once /// @dev Initialize the upgradable contract /// @param _strategyToken address of the strategy token. Here imUSD /// @param _underlyingToken address of the token deposited. here mUSD /// @param _vault address of the of the vault /// @param _uniswapV2Router02 address of the uniswap router /// @param _routerPath path to swap the gov tokens function initialize( address _strategyToken, address _underlyingToken, address _vault, address _uniswapV2Router02, address[] calldata _routerPath, address _owner ) public initializer { OwnableUpgradeable.__Ownable_init(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); require(token == address(0), "Token is already initialized"); //----- // -------// // this contract tokenizes the staked imUSD position strategyToken = address(this); token = _underlyingToken; underlyingToken = IERC20Detailed(_underlyingToken); tokenDecimals = IERC20Detailed(_underlyingToken).decimals(); oneToken = 10**(tokenDecimals); imUSD = ISavingsContractV2(_strategyToken); vault = IVault(_vault); govToken = vault.getRewardToken(); uniswapRouterPath = _routerPath; uniswapV2Router02 = IUniswapV2Router02(_uniswapV2Router02); releaseBlocksPeriod = 6400; // ~24 hours ERC20Upgradeable.__ERC20_init("Idle MStable Strategy Token", string(abi.encodePacked("idleMS", underlyingToken.symbol()))); lastIndexedTime = block.timestamp; //------//-------// transferOwnership(_owner); IERC20Detailed(_underlyingToken).approve(_strategyToken, type(uint256).max); ISavingsContractV2(_strategyToken).approve(_vault, type(uint256).max); } /// @notice redeem the rewards. Claims all possible rewards /// @return rewards amount of underlyings (mUSD) received after selling rewards function redeemRewards() external onlyOwner returns (uint256[] memory rewards) { _claimGovernanceTokens(0); rewards = new uint256[](1); rewards[0] = _swapGovTokenOnUniswapAndDepositToVault(0); // will redeem whatever possible reward is available } /// @notice redeem the rewards. Claims reward as per the _extraData /// @param _extraData must contain the minimum liquidity to receive, start round and end round round for which the reward is being claimed /// @return rewards amount of underlyings (mUSD) received after selling rewards function redeemRewards(bytes calldata _extraData) external override onlyIdleCDO returns (uint256[] memory rewards) { (uint256 minLiquidityTokenToReceive, uint256 endRound) = abi.decode(_extraData, (uint256, uint256)); _claimGovernanceTokens(endRound); rewards = new uint256[](1); rewards[0] = _swapGovTokenOnUniswapAndDepositToVault(minLiquidityTokenToReceive); } /// @notice unused in MStable Strategy function pullStkAAVE() external pure override returns (uint256) { return 0; } /// @notice net price in underlyings of 1 strategyToken /// @return _price function price() public view override returns (uint256 _price) { uint256 _totalSupply = totalSupply(); if (_totalSupply == 0) { _price = oneToken; } else { _price = (totalLpTokensStaked - _lockedLpTokens()) * oneToken / _totalSupply; } } /// @notice Get the reward token /// @return _rewards array of reward token (empty as rewards are handled in this strategy) function getRewardTokens() external pure override returns (address[] memory _rewards) { return _rewards; } /// @notice Deposit the underlying token to vault /// @param _amount number of tokens to deposit /// @return minted number of reward tokens minted function deposit(uint256 _amount) external override onlyIdleCDO returns (uint256 minted) { if (_amount > 0) { underlyingToken.transferFrom(msg.sender, address(this), _amount); minted = _depositToVault(_amount, true); } } /// @notice Internal function to deposit the underlying tokens to the vault /// @param _amount amount of tokens to deposit /// @param _shouldMint amount of tokens to deposit /// @return _minted number of reward tokens minted function _depositToVault(uint256 _amount, bool _shouldMint) internal returns (uint256 _minted) { ISavingsContractV2 _imUSD = imUSD; lastIndexAmount = lastIndexAmount + _amount; lastIndexedTime = block.timestamp; // mint imUSD with mUSD _imUSD.depositSavings(_amount); // stake imUSD in Meta vault uint256 _imUSDBal = _imUSD.balanceOf(address(this)); vault.stake(_imUSDBal); if (_shouldMint) { _minted = _amount * oneToken / price(); _mint(msg.sender, _minted); } totalLpTokensStaked += _amount; } /// @notice Redeem Tokens /// @param _amount amount of strategy tokens to redeem /// @return Amount of underlying tokens received function redeem(uint256 _amount) external override onlyIdleCDO returns (uint256) { return _redeem(_amount, price()); } /// @notice Redeem Tokens /// @param _amount amount of underlying tokens to redeem /// @return Amount of underlying tokens received function redeemUnderlying(uint256 _amount) external override onlyIdleCDO returns (uint256) { uint256 _price = price(); uint256 _strategyTokens = (_amount * oneToken) / _price; return _redeem(_strategyTokens, _price); } /// @notice Approximate APR /// @return APR function getApr() external view override returns (uint256) { uint256 rawBalance = vault.rawBalanceOf(address(this)); uint256 expectedUnderlyingAmount = imUSD.creditsToUnderlying(rawBalance); uint256 gain = expectedUnderlyingAmount - lastIndexAmount; if (gain == 0) { return 0; } uint256 time = block.timestamp - lastIndexedTime; uint256 gainPerc = (gain * 10**20) / lastIndexAmount; uint256 apr = (YEAR / time) * gainPerc; return apr; } /* -------- internal functions ------------- */ /// @notice Internal function to redeem the underlying tokens /// @param _amount Amount of strategy tokens /// @return massetReceived Amount of underlying tokens received function _redeem(uint256 _amount, uint256 _price) internal returns (uint256 massetReceived) { lastIndexAmount = lastIndexAmount - _amount; lastIndexedTime = block.timestamp; ISavingsContractV2 _imUSD = imUSD; // mUSD we want back uint256 redeemed = (_amount * _price) / oneToken; uint256 imUSDToRedeem = _imUSD.underlyingToCredits(redeemed); totalLpTokensStaked -= redeemed; _burn(msg.sender, _amount); vault.withdraw(imUSDToRedeem); massetReceived = _imUSD.redeemCredits(imUSDToRedeem); underlyingToken.transfer(msg.sender, massetReceived); } /// @notice Function to swap the governance tokens on uniswapV2 /// @param minLiquidityTokenToReceive minimun number of tokens to that need to be received /// @return _bal amount of underlyings (mUSD) received function _swapGovTokenOnUniswapAndDepositToVault(uint256 minLiquidityTokenToReceive) internal returns (uint256 _bal) { IERC20Detailed _govToken = IERC20Detailed(govToken); uint256 govTokensToSend = _govToken.balanceOf(address(this)); IUniswapV2Router02 _uniswapV2Router02 = uniswapV2Router02; _govToken.approve(address(_uniswapV2Router02), govTokensToSend); _uniswapV2Router02.swapExactTokensForTokens( govTokensToSend, minLiquidityTokenToReceive, uniswapRouterPath, address(this), block.timestamp ); _bal = underlyingToken.balanceOf(address(this)); _depositToVault(_bal, false); // save the block in which rewards are swapped and the amount latestHarvestBlock = block.number; totalLpTokensLocked = _bal; } /// @notice Claim governance tokens /// @param endRound End Round from which the Governance tokens must be claimed function claimGovernanceTokens(uint256 endRound) external onlyOwner { _claimGovernanceTokens(endRound); } /// @notice Claim governance tokens /// @param endRound End Round from which the Governance tokens must be claimed function _claimGovernanceTokens(uint256 endRound) internal { if (endRound == 0) { (, , endRound) = vault.unclaimedRewards(address(this)); } vault.claimRewards(rewardLastRound, endRound); rewardLastRound = endRound; } /// @notice Change the uniswap router path /// @param newPath New Path /// @dev operation can be only done by the owner of the contract function changeUniswapRouterPath(address[] memory newPath) public onlyOwner { uniswapRouterPath = newPath; } /// @notice allow to update whitelisted address function setWhitelistedCDO(address _cdo) external onlyOwner { require(_cdo != address(0), "IS_0"); idleCDO = _cdo; } /// @notice allow to update whitelisted address function setReleaseBlocksPeriod(uint256 _period) external onlyOwner { releaseBlocksPeriod = _period; } /// @notice function _lockedLpTokens() internal view returns (uint256 _locked) { uint256 _releaseBlocksPeriod = releaseBlocksPeriod; uint256 _blocksSinceLastHarvest = block.number - latestHarvestBlock; uint256 _totalLockedLpTokens = totalLpTokensLocked; if (_totalLockedLpTokens > 0 && _blocksSinceLastHarvest < _releaseBlocksPeriod) { // progressively release harvested rewards _locked = _totalLockedLpTokens * (_releaseBlocksPeriod - _blocksSinceLastHarvest) / _releaseBlocksPeriod; } } /// @notice Modifier to make sure that caller os only the idleCDO contract modifier onlyIdleCDO() { require(idleCDO == msg.sender, "Only IdleCDO can call"); _; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; interface IIdleCDOStrategy { function strategyToken() external view returns(address); function token() external view returns(address); function tokenDecimals() external view returns(uint256); function oneToken() external view returns(uint256); function redeemRewards(bytes calldata _extraData) external returns(uint256[] memory); function pullStkAAVE() external returns(uint256); function price() external view returns(uint256); function getRewardTokens() external view returns(address[] memory); function deposit(uint256 _amount) external returns(uint256); // _amount in `strategyToken` function redeem(uint256 _amount) external returns(uint256); // _amount in `token` function redeemUnderlying(uint256 _amount) external returns(uint256); function getApr() external view returns(uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; interface IMAsset { function redeem( address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient ) external returns (uint256 outputQuantity); function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external returns (uint256 mintOutput); 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); function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external returns (uint256 swapOutput); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; interface ISavingsContractV2 { // DEPRECATED but still backwards compatible function redeem(uint256 _amount) external returns (uint256 massetReturned); function creditBalances(address) external view returns (uint256); // V1 & V2 (use balanceOf) // -------------------------------------------- function depositInterest(uint256 _amount) external; // V1 & V2 function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); // V1 & V2 function depositSavings(uint256 _amount, address _beneficiary) external returns (uint256 creditsIssued); // V2 function redeemCredits(uint256 _amount) external returns (uint256 underlyingReturned); // V2 function redeemUnderlying(uint256 _amount) external returns (uint256 creditsBurned); // V2 function exchangeRate() external view returns (uint256); // V1 & V2 function balanceOfUnderlying(address _user) external view returns (uint256 balance); // V2 function underlyingToCredits(uint256 _credits) external view returns (uint256 underlying); // V2 function creditsToUnderlying(uint256 _underlying) external view returns (uint256 credits); // V2 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); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IERC20Detailed is IERC20Upgradeable { function name() external view returns(string memory); function symbol() external view returns(string memory); function decimals() external view returns(uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.10; interface IVault { function stake(uint256 _amount) external; function stake(address _beneficiary, uint256 _amount) external; function exit() external; function exit(uint256 _first, uint256 _last) external; function withdraw(uint256 _amount) external; function rawBalanceOf(address _account) external view returns (uint256); function claimRewards() external; function claimRewards(uint256 _first, uint256 _last) external; function boostDirector() external view returns (address); function getRewardToken() external view returns (address); function notifyRewardAmount(uint256 _reward) external; function unclaimedRewards(address _account) external view returns ( uint256 amount, uint256 first, uint256 last ); } pragma solidity >=0.6.2; import "./IUniswapV2Router01.sol"; 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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 pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @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 this function is * overloaded; * * 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 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { 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 // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); } } } }
Redeem Tokens _amount amount of strategy tokens to redeem return Amount of underlying tokens received
function redeem(uint256 _amount) external override onlyIdleCDO returns (uint256) { return _redeem(_amount, price()); }
13,879,719
pragma solidity 0.4.25; /// @title provides subject to role checking logic contract IAccessPolicy { //////////////////////// // Public functions //////////////////////// /// @notice We don't make this function constant to allow for state-updating access controls such as rate limiting. /// @dev checks if subject belongs to requested role for particular object /// @param subject address to be checked against role, typically msg.sender /// @param role identifier of required role /// @param object contract instance context for role checking, typically contract requesting the check /// @param verb additional data, in current AccessControll implementation msg.sig /// @return if subject belongs to a role function allowed( address subject, bytes32 role, address object, bytes4 verb ) public returns (bool); } /// @title enables access control in implementing contract /// @dev see AccessControlled for implementation contract IAccessControlled { //////////////////////// // Events //////////////////////// /// @dev must log on access policy change event LogAccessPolicyChanged( address controller, IAccessPolicy oldPolicy, IAccessPolicy newPolicy ); //////////////////////// // Public functions //////////////////////// /// @dev allows to change access control mechanism for this contract /// this method must be itself access controlled, see AccessControlled implementation and notice below /// @notice it is a huge issue for Solidity that modifiers are not part of function signature /// then interfaces could be used for example to control access semantics /// @param newPolicy new access policy to controll this contract /// @param newAccessController address of ROLE_ACCESS_CONTROLLER of new policy that can set access to this contract function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController) public; function accessPolicy() public constant returns (IAccessPolicy); } contract StandardRoles { //////////////////////// // Constants //////////////////////// // @notice Soldity somehow doesn't evaluate this compile time // @dev role which has rights to change permissions and set new policy in contract, keccak256("AccessController") bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da; } /// @title Granular code execution permissions /// @notice Intended to replace existing Ownable pattern with more granular permissions set to execute smart contract functions /// for each function where 'only' modifier is applied, IAccessPolicy implementation is called to evaluate if msg.sender belongs to required role for contract being called. /// Access evaluation specific belong to IAccessPolicy implementation, see RoleBasedAccessPolicy for details. /// @dev Should be inherited by a contract requiring such permissions controll. IAccessPolicy must be provided in constructor. Access policy may be replaced to a different one /// by msg.sender with ROLE_ACCESS_CONTROLLER role contract AccessControlled is IAccessControlled, StandardRoles { //////////////////////// // Mutable state //////////////////////// IAccessPolicy private _accessPolicy; //////////////////////// // Modifiers //////////////////////// /// @dev limits function execution only to senders assigned to required 'role' modifier only(bytes32 role) { require(_accessPolicy.allowed(msg.sender, role, this, msg.sig)); _; } //////////////////////// // Constructor //////////////////////// constructor(IAccessPolicy policy) internal { require(address(policy) != 0x0); _accessPolicy = policy; } //////////////////////// // Public functions //////////////////////// // // Implements IAccessControlled // function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController) public only(ROLE_ACCESS_CONTROLLER) { // ROLE_ACCESS_CONTROLLER must be present // under the new policy. This provides some // protection against locking yourself out. require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig)); // We can now safely set the new policy without foot shooting. IAccessPolicy oldPolicy = _accessPolicy; _accessPolicy = newPolicy; // Log event emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy); } function accessPolicy() public constant returns (IAccessPolicy) { return _accessPolicy; } } /// @title standard access roles of the Platform /// @dev constants are kept in CODE not in STORAGE so they are comparatively cheap contract AccessRoles { //////////////////////// // Constants //////////////////////// // NOTE: All roles are set to the keccak256 hash of the // CamelCased role name, i.e. // ROLE_LOCKED_ACCOUNT_ADMIN = keccak256("LockedAccountAdmin") // May issue (generate) Neumarks bytes32 internal constant ROLE_NEUMARK_ISSUER = 0x921c3afa1f1fff707a785f953a1e197bd28c9c50e300424e015953cbf120c06c; // May burn Neumarks it owns bytes32 internal constant ROLE_NEUMARK_BURNER = 0x19ce331285f41739cd3362a3ec176edffe014311c0f8075834fdd19d6718e69f; // May create new snapshots on Neumark bytes32 internal constant ROLE_SNAPSHOT_CREATOR = 0x08c1785afc57f933523bc52583a72ce9e19b2241354e04dd86f41f887e3d8174; // May enable/disable transfers on Neumark bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19; // may reclaim tokens/ether from contracts supporting IReclaimable interface bytes32 internal constant ROLE_RECLAIMER = 0x0542bbd0c672578966dcc525b30aa16723bb042675554ac5b0362f86b6e97dc5; // represents legally platform operator in case of forks and contracts with legal agreement attached. keccak256("PlatformOperatorRepresentative") bytes32 internal constant ROLE_PLATFORM_OPERATOR_REPRESENTATIVE = 0xb2b321377653f655206f71514ff9f150d0822d062a5abcf220d549e1da7999f0; // allows to deposit EUR-T and allow addresses to send and receive EUR-T. keccak256("EurtDepositManager") bytes32 internal constant ROLE_EURT_DEPOSIT_MANAGER = 0x7c8ecdcba80ce87848d16ad77ef57cc196c208fc95c5638e4a48c681a34d4fe7; // allows to register identities and change associated claims keccak256("IdentityManager") bytes32 internal constant ROLE_IDENTITY_MANAGER = 0x32964e6bc50f2aaab2094a1d311be8bda920fc4fb32b2fb054917bdb153a9e9e; // allows to replace controller on euro token and to destroy tokens without withdraw kecckak256("EurtLegalManager") bytes32 internal constant ROLE_EURT_LEGAL_MANAGER = 0x4eb6b5806954a48eb5659c9e3982d5e75bfb2913f55199877d877f157bcc5a9b; // allows to change known interfaces in universe kecckak256("UniverseManager") bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738; // allows to exchange gas for EUR-T keccak("GasExchange") bytes32 internal constant ROLE_GAS_EXCHANGE = 0x9fe43636e0675246c99e96d7abf9f858f518b9442c35166d87f0934abef8a969; // allows to set token exchange rates keccak("TokenRateOracle") bytes32 internal constant ROLE_TOKEN_RATE_ORACLE = 0xa80c3a0c8a5324136e4c806a778583a2a980f378bdd382921b8d28dcfe965585; } contract IEthereumForkArbiter { //////////////////////// // Events //////////////////////// event LogForkAnnounced( string name, string url, uint256 blockNumber ); event LogForkSigned( uint256 blockNumber, bytes32 blockHash ); //////////////////////// // Public functions //////////////////////// function nextForkName() public constant returns (string); function nextForkUrl() public constant returns (string); function nextForkBlockNumber() public constant returns (uint256); function lastSignedBlockNumber() public constant returns (uint256); function lastSignedBlockHash() public constant returns (bytes32); function lastSignedTimestamp() public constant returns (uint256); } /** * @title legally binding smart contract * @dev General approach to paring legal and smart contracts: * 1. All terms and agreement are between two parties: here between smart conctract legal representation and platform investor. * 2. Parties are represented by public Ethereum addresses. Platform investor is and address that holds and controls funds and receives and controls Neumark token * 3. Legal agreement has immutable part that corresponds to smart contract code and mutable part that may change for example due to changing regulations or other externalities that smart contract does not control. * 4. There should be a provision in legal document that future changes in mutable part cannot change terms of immutable part. * 5. Immutable part links to corresponding smart contract via its address. * 6. Additional provision should be added if smart contract supports it * a. Fork provision * b. Bugfixing provision (unilateral code update mechanism) * c. Migration provision (bilateral code update mechanism) * * Details on Agreement base class: * 1. We bind smart contract to legal contract by storing uri (preferably ipfs or hash) of the legal contract in the smart contract. It is however crucial that such binding is done by smart contract legal representation so transaction establishing the link must be signed by respective wallet ('amendAgreement') * 2. Mutable part of agreement may change. We should be able to amend the uri later. Previous amendments should not be lost and should be retrievable (`amendAgreement` and 'pastAgreement' functions). * 3. It is up to deriving contract to decide where to put 'acceptAgreement' modifier. However situation where there is no cryptographic proof that given address was really acting in the transaction should be avoided, simplest example being 'to' address in `transfer` function of ERC20. * **/ contract IAgreement { //////////////////////// // Events //////////////////////// event LogAgreementAccepted( address indexed accepter ); event LogAgreementAmended( address contractLegalRepresentative, string agreementUri ); /// @dev should have access restrictions so only contractLegalRepresentative may call function amendAgreement(string agreementUri) public; /// returns information on last amendment of the agreement /// @dev MUST revert if no agreements were set function currentAgreement() public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ); /// returns information on amendment with index /// @dev MAY revert on non existing amendment, indexing starts from 0 function pastAgreement(uint256 amendmentIndex) public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ); /// returns the number of block at wchich `signatory` signed agreement /// @dev MUST return 0 if not signed function agreementSignedAtBlock(address signatory) public constant returns (uint256 blockNo); /// returns number of amendments made by contractLegalRepresentative function amendmentsCount() public constant returns (uint256); } /** * @title legally binding smart contract * @dev read IAgreement for details **/ contract Agreement is IAgreement, AccessControlled, AccessRoles { //////////////////////// // Type declarations //////////////////////// /// @notice agreement with signature of the platform operator representative struct SignedAgreement { address contractLegalRepresentative; uint256 signedBlockTimestamp; string agreementUri; } //////////////////////// // Immutable state //////////////////////// IEthereumForkArbiter private ETHEREUM_FORK_ARBITER; //////////////////////// // Mutable state //////////////////////// // stores all amendments to the agreement, first amendment is the original SignedAgreement[] private _amendments; // stores block numbers of all addresses that signed the agreement (signatory => block number) mapping(address => uint256) private _signatories; //////////////////////// // Modifiers //////////////////////// /// @notice logs that agreement was accepted by platform user /// @dev intended to be added to functions that if used make 'accepter' origin to enter legally binding agreement modifier acceptAgreement(address accepter) { acceptAgreementInternal(accepter); _; } modifier onlyLegalRepresentative(address legalRepresentative) { require(mCanAmend(legalRepresentative)); _; } //////////////////////// // Constructor //////////////////////// constructor(IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter) AccessControlled(accessPolicy) internal { require(forkArbiter != IEthereumForkArbiter(0x0)); ETHEREUM_FORK_ARBITER = forkArbiter; } //////////////////////// // Public functions //////////////////////// function amendAgreement(string agreementUri) public onlyLegalRepresentative(msg.sender) { SignedAgreement memory amendment = SignedAgreement({ contractLegalRepresentative: msg.sender, signedBlockTimestamp: block.timestamp, agreementUri: agreementUri }); _amendments.push(amendment); emit LogAgreementAmended(msg.sender, agreementUri); } function ethereumForkArbiter() public constant returns (IEthereumForkArbiter) { return ETHEREUM_FORK_ARBITER; } function currentAgreement() public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ) { require(_amendments.length > 0); uint256 last = _amendments.length - 1; SignedAgreement storage amendment = _amendments[last]; return ( amendment.contractLegalRepresentative, amendment.signedBlockTimestamp, amendment.agreementUri, last ); } function pastAgreement(uint256 amendmentIndex) public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ) { SignedAgreement storage amendment = _amendments[amendmentIndex]; return ( amendment.contractLegalRepresentative, amendment.signedBlockTimestamp, amendment.agreementUri, amendmentIndex ); } function agreementSignedAtBlock(address signatory) public constant returns (uint256 blockNo) { return _signatories[signatory]; } function amendmentsCount() public constant returns (uint256) { return _amendments.length; } //////////////////////// // Internal functions //////////////////////// /// provides direct access to derived contract function acceptAgreementInternal(address accepter) internal { if(_signatories[accepter] == 0) { require(_amendments.length > 0); _signatories[accepter] = block.number; emit LogAgreementAccepted(accepter); } } // // MAgreement Internal interface (todo: extract) // /// default amend permission goes to ROLE_PLATFORM_OPERATOR_REPRESENTATIVE function mCanAmend(address legalRepresentative) internal returns (bool) { return accessPolicy().allowed(legalRepresentative, ROLE_PLATFORM_OPERATOR_REPRESENTATIVE, this, msg.sig); } } /// @title describes layout of claims in 256bit records stored for identities /// @dev intended to be derived by contracts requiring access to particular claims contract IdentityRecord { //////////////////////// // Types //////////////////////// /// @dev here the idea is to have claims of size of uint256 and use this struct /// to translate in and out of this struct. until we do not cross uint256 we /// have binary compatibility struct IdentityClaims { bool isVerified; // 1 bit bool isSophisticatedInvestor; // 1 bit bool hasBankAccount; // 1 bit bool accountFrozen; // 1 bit // uint252 reserved } //////////////////////// // Internal functions //////////////////////// /// translates uint256 to struct function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) { // for memory layout of struct, each field below word length occupies whole word assembly { mstore(claims, and(data, 0x1)) mstore(add(claims, 0x20), div(and(data, 0x2), 0x2)) mstore(add(claims, 0x40), div(and(data, 0x4), 0x4)) mstore(add(claims, 0x60), div(and(data, 0x8), 0x8)) } } } /// @title interface storing and retrieve 256bit claims records for identity /// actual format of record is decoupled from storage (except maximum size) contract IIdentityRegistry { //////////////////////// // Events //////////////////////// /// provides information on setting claims event LogSetClaims( address indexed identity, bytes32 oldClaims, bytes32 newClaims ); //////////////////////// // Public functions //////////////////////// /// get claims for identity function getClaims(address identity) public constant returns (bytes32); /// set claims for identity /// @dev odlClaims and newClaims used for optimistic locking. to override with newClaims /// current claims must be oldClaims function setClaims(address identity, bytes32 oldClaims, bytes32 newClaims) public; } /// @title known interfaces (services) of the platform /// "known interface" is a unique id of service provided by the platform and discovered via Universe contract /// it does not refer to particular contract/interface ABI, particular service may be delivered via different implementations /// however for a few contracts we commit platform to particular implementation (all ICBM Contracts, Universe itself etc.) /// @dev constants are kept in CODE not in STORAGE so they are comparatively cheap contract KnownInterfaces { //////////////////////// // Constants //////////////////////// // NOTE: All interface are set to the keccak256 hash of the // CamelCased interface or singleton name, i.e. // KNOWN_INTERFACE_NEUMARK = keccak256("Neumark") // EIP 165 + EIP 820 should be use instead but it seems they are far from finished // also interface signature should be build automatically by solidity. otherwise it is a pure hassle // neumark token interface and sigleton keccak256("Neumark") bytes4 internal constant KNOWN_INTERFACE_NEUMARK = 0xeb41a1bd; // ether token interface and singleton keccak256("EtherToken") bytes4 internal constant KNOWN_INTERFACE_ETHER_TOKEN = 0x8cf73cf1; // euro token interface and singleton keccak256("EuroToken") bytes4 internal constant KNOWN_INTERFACE_EURO_TOKEN = 0x83c3790b; // identity registry interface and singleton keccak256("IIdentityRegistry") bytes4 internal constant KNOWN_INTERFACE_IDENTITY_REGISTRY = 0x0a72e073; // currency rates oracle interface and singleton keccak256("ITokenExchangeRateOracle") bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE = 0xc6e5349e; // fee disbursal interface and singleton keccak256("IFeeDisbursal") bytes4 internal constant KNOWN_INTERFACE_FEE_DISBURSAL = 0xf4c848e8; // platform portfolio holding equity tokens belonging to NEU holders keccak256("IPlatformPortfolio"); bytes4 internal constant KNOWN_INTERFACE_PLATFORM_PORTFOLIO = 0xaa1590d0; // token exchange interface and singleton keccak256("ITokenExchange") bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE = 0xddd7a521; // service exchanging euro token for gas ("IGasTokenExchange") bytes4 internal constant KNOWN_INTERFACE_GAS_EXCHANGE = 0x89dbc6de; // access policy interface and singleton keccak256("IAccessPolicy") bytes4 internal constant KNOWN_INTERFACE_ACCESS_POLICY = 0xb05049d9; // euro lock account (upgraded) keccak256("LockedAccount:Euro") bytes4 internal constant KNOWN_INTERFACE_EURO_LOCK = 0x2347a19e; // ether lock account (upgraded) keccak256("LockedAccount:Ether") bytes4 internal constant KNOWN_INTERFACE_ETHER_LOCK = 0x978a6823; // icbm euro lock account keccak256("ICBMLockedAccount:Euro") bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_LOCK = 0x36021e14; // ether lock account (upgraded) keccak256("ICBMLockedAccount:Ether") bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_LOCK = 0x0b58f006; // ether token interface and singleton keccak256("ICBMEtherToken") bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_TOKEN = 0xae8b50b9; // euro token interface and singleton keccak256("ICBMEuroToken") bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_TOKEN = 0xc2c6cd72; // ICBM commitment interface interface and singleton keccak256("ICBMCommitment") bytes4 internal constant KNOWN_INTERFACE_ICBM_COMMITMENT = 0x7f2795ef; // ethereum fork arbiter interface and singleton keccak256("IEthereumForkArbiter") bytes4 internal constant KNOWN_INTERFACE_FORK_ARBITER = 0x2fe7778c; // Platform terms interface and singletong keccak256("PlatformTerms") bytes4 internal constant KNOWN_INTERFACE_PLATFORM_TERMS = 0x75ecd7f8; // for completness we define Universe service keccak256("Universe"); bytes4 internal constant KNOWN_INTERFACE_UNIVERSE = 0xbf202454; // ETO commitment interface (collection) keccak256("ICommitment") bytes4 internal constant KNOWN_INTERFACE_COMMITMENT = 0xfa0e0c60; // Equity Token Controller interface (collection) keccak256("IEquityTokenController") bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN_CONTROLLER = 0xfa30b2f1; // Equity Token interface (collection) keccak256("IEquityToken") bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN = 0xab9885bb; } contract IsContract { //////////////////////// // Internal functions //////////////////////// function isContract(address addr) internal constant returns (bool) { uint256 size; // takes 700 gas assembly { size := extcodesize(addr) } return size > 0; } } contract NeumarkIssuanceCurve { //////////////////////// // Constants //////////////////////// // maximum number of neumarks that may be created uint256 private constant NEUMARK_CAP = 1500000000000000000000000000; // initial neumark reward fraction (controls curve steepness) uint256 private constant INITIAL_REWARD_FRACTION = 6500000000000000000; // stop issuing new Neumarks above this Euro value (as it goes quickly to zero) uint256 private constant ISSUANCE_LIMIT_EUR_ULPS = 8300000000000000000000000000; // approximate curve linearly above this Euro value uint256 private constant LINEAR_APPROX_LIMIT_EUR_ULPS = 2100000000000000000000000000; uint256 private constant NEUMARKS_AT_LINEAR_LIMIT_ULPS = 1499832501287264827896539871; uint256 private constant TOT_LINEAR_NEUMARKS_ULPS = NEUMARK_CAP - NEUMARKS_AT_LINEAR_LIMIT_ULPS; uint256 private constant TOT_LINEAR_EUR_ULPS = ISSUANCE_LIMIT_EUR_ULPS - LINEAR_APPROX_LIMIT_EUR_ULPS; //////////////////////// // Public functions //////////////////////// /// @notice returns additional amount of neumarks issued for euroUlps at totalEuroUlps /// @param totalEuroUlps actual curve position from which neumarks will be issued /// @param euroUlps amount against which neumarks will be issued function incremental(uint256 totalEuroUlps, uint256 euroUlps) public pure returns (uint256 neumarkUlps) { require(totalEuroUlps + euroUlps >= totalEuroUlps); uint256 from = cumulative(totalEuroUlps); uint256 to = cumulative(totalEuroUlps + euroUlps); // as expansion is not monotonic for large totalEuroUlps, assert below may fail // example: totalEuroUlps=1.999999999999999999999000000e+27 and euroUlps=50 assert(to >= from); return to - from; } /// @notice returns amount of euro corresponding to burned neumarks /// @param totalEuroUlps actual curve position from which neumarks will be burned /// @param burnNeumarkUlps amount of neumarks to burn function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps) public pure returns (uint256 euroUlps) { uint256 totalNeumarkUlps = cumulative(totalEuroUlps); require(totalNeumarkUlps >= burnNeumarkUlps); uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps; uint newTotalEuroUlps = cumulativeInverse(fromNmk, 0, totalEuroUlps); // yes, this may overflow due to non monotonic inverse function assert(totalEuroUlps >= newTotalEuroUlps); return totalEuroUlps - newTotalEuroUlps; } /// @notice returns amount of euro corresponding to burned neumarks /// @param totalEuroUlps actual curve position from which neumarks will be burned /// @param burnNeumarkUlps amount of neumarks to burn /// @param minEurUlps euro amount to start inverse search from, inclusive /// @param maxEurUlps euro amount to end inverse search to, inclusive function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) public pure returns (uint256 euroUlps) { uint256 totalNeumarkUlps = cumulative(totalEuroUlps); require(totalNeumarkUlps >= burnNeumarkUlps); uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps; uint newTotalEuroUlps = cumulativeInverse(fromNmk, minEurUlps, maxEurUlps); // yes, this may overflow due to non monotonic inverse function assert(totalEuroUlps >= newTotalEuroUlps); return totalEuroUlps - newTotalEuroUlps; } /// @notice finds total amount of neumarks issued for given amount of Euro /// @dev binomial expansion does not guarantee monotonicity on uint256 precision for large euroUlps /// function below is not monotonic function cumulative(uint256 euroUlps) public pure returns(uint256 neumarkUlps) { // Return the cap if euroUlps is above the limit. if (euroUlps >= ISSUANCE_LIMIT_EUR_ULPS) { return NEUMARK_CAP; } // use linear approximation above limit below // binomial expansion does not guarantee monotonicity on uint256 precision for large euroUlps if (euroUlps >= LINEAR_APPROX_LIMIT_EUR_ULPS) { // (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS) is small so expression does not overflow return NEUMARKS_AT_LINEAR_LIMIT_ULPS + (TOT_LINEAR_NEUMARKS_ULPS * (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS)) / TOT_LINEAR_EUR_ULPS; } // Approximate cap-cap·(1-1/D)^n using the Binomial expansion // http://galileo.phys.virginia.edu/classes/152.mf1i.spring02/Exponential_Function.htm // Function[imax, -CAP*Sum[(-IR*EUR/CAP)^i/Factorial[i], {i, imax}]] // which may be simplified to // Function[imax, -CAP*Sum[(EUR)^i/(Factorial[i]*(-d)^i), {i, 1, imax}]] // where d = cap/initial_reward uint256 d = 230769230769230769230769231; // NEUMARK_CAP / INITIAL_REWARD_FRACTION uint256 term = NEUMARK_CAP; uint256 sum = 0; uint256 denom = d; do assembly { // We use assembler primarily to avoid the expensive // divide-by-zero check solc inserts for the / operator. term := div(mul(term, euroUlps), denom) sum := add(sum, term) denom := add(denom, d) // sub next term as we have power of negative value in the binomial expansion term := div(mul(term, euroUlps), denom) sum := sub(sum, term) denom := add(denom, d) } while (term != 0); return sum; } /// @notice find issuance curve inverse by binary search /// @param neumarkUlps neumark amount to compute inverse for /// @param minEurUlps minimum search range for the inverse, inclusive /// @param maxEurUlps maxium search range for the inverse, inclusive /// @dev in case of approximate search (no exact inverse) upper element of minimal search range is returned /// @dev in case of many possible inverses, the lowest one will be used (if range permits) /// @dev corresponds to a linear search that returns first euroUlp value that has cumulative() equal or greater than neumarkUlps function cumulativeInverse(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) public pure returns (uint256 euroUlps) { require(maxEurUlps >= minEurUlps); require(cumulative(minEurUlps) <= neumarkUlps); require(cumulative(maxEurUlps) >= neumarkUlps); uint256 min = minEurUlps; uint256 max = maxEurUlps; // Binary search while (max > min) { uint256 mid = (max + min) / 2; uint256 val = cumulative(mid); // exact solution should not be used, a late points of the curve when many euroUlps are needed to // increase by one nmkUlp this will lead to "indeterministic" inverse values that depend on the initial min and max // and further binary division -> you can land at any of the euro value that is mapped to the same nmk value // with condition below removed, binary search will point to the lowest eur value possible which is good because it cannot be exploited even with 0 gas costs /* if (val == neumarkUlps) { return mid; }*/ // NOTE: approximate search (no inverse) must return upper element of the final range // last step of approximate search is always (min, min+1) so new mid is (2*min+1)/2 => min // so new min = mid + 1 = max which was upper range. and that ends the search // NOTE: when there are multiple inverses for the same neumarkUlps, the `max` will be dragged down // by `max = mid` expression to the lowest eur value of inverse. works only for ranges that cover all points of multiple inverse if (val < neumarkUlps) { min = mid + 1; } else { max = mid; } } // NOTE: It is possible that there is no inverse // for example curve(0) = 0 and curve(1) = 6, so // there is no value y such that curve(y) = 5. // When there is no inverse, we must return upper element of last search range. // This has the effect of reversing the curve less when // burning Neumarks. This ensures that Neumarks can always // be burned. It also ensure that the total supply of Neumarks // remains below the cap. return max; } function neumarkCap() public pure returns (uint256) { return NEUMARK_CAP; } function initialRewardFraction() public pure returns (uint256) { return INITIAL_REWARD_FRACTION; } } contract IBasicToken { //////////////////////// // Events //////////////////////// event Transfer( address indexed from, address indexed to, uint256 amount ); //////////////////////// // Public functions //////////////////////// /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint256); /// @param owner The address that's balance is being requested /// @return The balance of `owner` at the current block function balanceOf(address owner) public constant returns (uint256 balance); /// @notice Send `amount` tokens to `to` from `msg.sender` /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address to, uint256 amount) public returns (bool success); } /// @title allows deriving contract to recover any token or ether that it has balance of /// @notice note that this opens your contracts to claims from various people saying they lost tokens and they want them back /// be ready to handle such claims /// @dev use with care! /// 1. ROLE_RECLAIMER is allowed to claim tokens, it's not returning tokens to original owner /// 2. in derived contract that holds any token by design you must override `reclaim` and block such possibility. /// see ICBMLockedAccount as an example contract Reclaimable is AccessControlled, AccessRoles { //////////////////////// // Constants //////////////////////// IBasicToken constant internal RECLAIM_ETHER = IBasicToken(0x0); //////////////////////// // Public functions //////////////////////// function reclaim(IBasicToken token) public only(ROLE_RECLAIMER) { address reclaimer = msg.sender; if(token == RECLAIM_ETHER) { reclaimer.transfer(address(this).balance); } else { uint256 balance = token.balanceOf(this); require(token.transfer(reclaimer, balance)); } } } /// @title advances snapshot id on demand /// @dev see Snapshot folder for implementation examples ie. DailyAndSnapshotable contract contract ISnapshotable { //////////////////////// // Events //////////////////////// /// @dev should log each new snapshot id created, including snapshots created automatically via MSnapshotPolicy event LogSnapshotCreated(uint256 snapshotId); //////////////////////// // Public functions //////////////////////// /// always creates new snapshot id which gets returned /// however, there is no guarantee that any snapshot will be created with this id, this depends on the implementation of MSnaphotPolicy function createSnapshot() public returns (uint256); /// upper bound of series snapshotIds for which there's a value function currentSnapshotId() public constant returns (uint256); } /// @title Abstracts snapshot id creation logics /// @dev Mixin (internal interface) of the snapshot policy which abstracts snapshot id creation logics from Snapshot contract /// @dev to be implemented and such implementation should be mixed with Snapshot-derived contract, see EveryBlock for simplest example of implementation and StandardSnapshotToken contract MSnapshotPolicy { //////////////////////// // Internal functions //////////////////////// // The snapshot Ids need to be strictly increasing. // Whenever the snaspshot id changes, a new snapshot will be created. // As long as the same snapshot id is being returned, last snapshot will be updated as this indicates that snapshot id didn't change // // Values passed to `hasValueAt` and `valuteAt` are required // to be less or equal to `mCurrentSnapshotId()`. function mAdvanceSnapshotId() internal returns (uint256); // this is a version of mAdvanceSnapshotId that does not modify state but MUST return the same value // it is required to implement ITokenSnapshots interface cleanly function mCurrentSnapshotId() internal constant returns (uint256); } /// @title creates new snapshot id on each day boundary /// @dev snapshot id is unix timestamp of current day boundary contract Daily is MSnapshotPolicy { //////////////////////// // Constants //////////////////////// // Floor[2**128 / 1 days] uint256 private MAX_TIMESTAMP = 3938453320844195178974243141571391; //////////////////////// // Constructor //////////////////////// /// @param start snapshotId from which to start generating values, used to prevent cloning from incompatible schemes /// @dev start must be for the same day or 0, required for token cloning constructor(uint256 start) internal { // 0 is invalid value as we are past unix epoch if (start > 0) { uint256 base = dayBase(uint128(block.timestamp)); // must be within current day base require(start >= base); // dayBase + 2**128 will not overflow as it is based on block.timestamp require(start < base + 2**128); } } //////////////////////// // Public functions //////////////////////// function snapshotAt(uint256 timestamp) public constant returns (uint256) { require(timestamp < MAX_TIMESTAMP); return dayBase(uint128(timestamp)); } //////////////////////// // Internal functions //////////////////////// // // Implements MSnapshotPolicy // function mAdvanceSnapshotId() internal returns (uint256) { return mCurrentSnapshotId(); } function mCurrentSnapshotId() internal constant returns (uint256) { // disregard overflows on block.timestamp, see MAX_TIMESTAMP return dayBase(uint128(block.timestamp)); } function dayBase(uint128 timestamp) internal pure returns (uint256) { // Round down to the start of the day (00:00 UTC) and place in higher 128bits return 2**128 * (uint256(timestamp) / 1 days); } } /// @title creates snapshot id on each day boundary and allows to create additional snapshots within a given day /// @dev snapshots are encoded in single uint256, where high 128 bits represents a day number (from unix epoch) and low 128 bits represents additional snapshots within given day create via ISnapshotable contract DailyAndSnapshotable is Daily, ISnapshotable { //////////////////////// // Mutable state //////////////////////// uint256 private _currentSnapshotId; //////////////////////// // Constructor //////////////////////// /// @param start snapshotId from which to start generating values /// @dev start must be for the same day or 0, required for token cloning constructor(uint256 start) internal Daily(start) { if (start > 0) { _currentSnapshotId = start; } } //////////////////////// // Public functions //////////////////////// // // Implements ISnapshotable // function createSnapshot() public returns (uint256) { uint256 base = dayBase(uint128(block.timestamp)); if (base > _currentSnapshotId) { // New day has started, create snapshot for midnight _currentSnapshotId = base; } else { // within single day, increase counter (assume 2**128 will not be crossed) _currentSnapshotId += 1; } // Log and return emit LogSnapshotCreated(_currentSnapshotId); return _currentSnapshotId; } //////////////////////// // Internal functions //////////////////////// // // Implements MSnapshotPolicy // function mAdvanceSnapshotId() internal returns (uint256) { uint256 base = dayBase(uint128(block.timestamp)); // New day has started if (base > _currentSnapshotId) { _currentSnapshotId = base; emit LogSnapshotCreated(base); } return _currentSnapshotId; } function mCurrentSnapshotId() internal constant returns (uint256) { uint256 base = dayBase(uint128(block.timestamp)); return base > _currentSnapshotId ? base : _currentSnapshotId; } } contract ITokenMetadata { //////////////////////// // Public functions //////////////////////// function symbol() public constant returns (string); function name() public constant returns (string); function decimals() public constant returns (uint8); } /// @title adds token metadata to token contract /// @dev see Neumark for example implementation contract TokenMetadata is ITokenMetadata { //////////////////////// // Immutable state //////////////////////// // The Token's name: e.g. DigixDAO Tokens string private NAME; // An identifier: e.g. REP string private SYMBOL; // Number of decimals of the smallest unit uint8 private DECIMALS; // An arbitrary versioning scheme string private VERSION; //////////////////////// // Constructor //////////////////////// /// @notice Constructor to set metadata /// @param tokenName Name of the new token /// @param decimalUnits Number of decimals of the new token /// @param tokenSymbol Token Symbol for the new token /// @param version Token version ie. when cloning is used constructor( string tokenName, uint8 decimalUnits, string tokenSymbol, string version ) public { NAME = tokenName; // Set the name SYMBOL = tokenSymbol; // Set the symbol DECIMALS = decimalUnits; // Set the decimals VERSION = version; } //////////////////////// // Public functions //////////////////////// function name() public constant returns (string) { return NAME; } function symbol() public constant returns (string) { return SYMBOL; } function decimals() public constant returns (uint8) { return DECIMALS; } function version() public constant returns (string) { return VERSION; } } contract IERC20Allowance { //////////////////////// // Events //////////////////////// event Approval( address indexed owner, address indexed spender, uint256 amount ); //////////////////////// // Public functions //////////////////////// /// @dev This function makes it easy to read the `allowed[]` map /// @param owner The address of the account that owns the token /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of owner that spender is allowed /// to spend function allowance(address owner, address spender) public constant returns (uint256 remaining); /// @notice `msg.sender` approves `spender` to spend `amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param spender The address of the account able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address spender, uint256 amount) public returns (bool success); /// @notice Send `amount` tokens to `to` from `from` on the condition it /// is approved by `from` /// @param from The address holding the tokens being transferred /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address from, address to, uint256 amount) public returns (bool success); } contract IERC20Token is IBasicToken, IERC20Allowance { } /// @title controls spending approvals /// @dev TokenAllowance observes this interface, Neumark contract implements it contract MTokenAllowanceController { //////////////////////// // Internal functions //////////////////////// /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param owner The address that calls `approve()` /// @param spender The spender in the `approve()` call /// @param amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function mOnApprove( address owner, address spender, uint256 amount ) internal returns (bool allow); /// @notice Allows to override allowance approved by the owner /// Primary role is to enable forced transfers, do not override if you do not like it /// Following behavior is expected in the observer /// approve() - should revert if mAllowanceOverride() > 0 /// allowance() - should return mAllowanceOverride() if set /// transferFrom() - should override allowance if mAllowanceOverride() > 0 /// @param owner An address giving allowance to spender /// @param spender An address getting a right to transfer allowance amount from the owner /// @return current allowance amount function mAllowanceOverride( address owner, address spender ) internal constant returns (uint256 allowance); } /// @title controls token transfers /// @dev BasicSnapshotToken observes this interface, Neumark contract implements it contract MTokenTransferController { //////////////////////// // Internal functions //////////////////////// /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param from The origin of the transfer /// @param to The destination of the transfer /// @param amount The amount of the transfer /// @return False if the controller does not authorize the transfer function mOnTransfer( address from, address to, uint256 amount ) internal returns (bool allow); } /// @title controls approvals and transfers /// @dev The token controller contract must implement these functions, see Neumark as example /// @dev please note that controller may be a separate contract that is called from mOnTransfer and mOnApprove functions contract MTokenController is MTokenTransferController, MTokenAllowanceController { } /// @title internal token transfer function /// @dev see BasicSnapshotToken for implementation contract MTokenTransfer { //////////////////////// // Internal functions //////////////////////// /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param from The address holding the tokens being transferred /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @dev reverts if transfer was not successful function mTransfer( address from, address to, uint256 amount ) internal; } contract IERC677Callback { //////////////////////// // Public functions //////////////////////// // NOTE: This call can be initiated by anyone. You need to make sure that // it is send by the token (`require(msg.sender == token)`) or make sure // amount is valid (`require(token.allowance(this) >= amount)`). function receiveApproval( address from, uint256 amount, address token, // IERC667Token bytes data ) public returns (bool success); } contract IERC677Allowance is IERC20Allowance { //////////////////////// // Public functions //////////////////////// /// @notice `msg.sender` approves `spender` to send `amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param spender The address of the contract able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address spender, uint256 amount, bytes extraData) public returns (bool success); } contract IERC677Token is IERC20Token, IERC677Allowance { } /// @title token spending approval and transfer /// @dev implements token approval and transfers and exposes relevant part of ERC20 and ERC677 approveAndCall /// may be mixed in with any basic token (implementing mTransfer) like BasicSnapshotToken or MintableSnapshotToken to add approval mechanism /// observes MTokenAllowanceController interface /// observes MTokenTransfer contract TokenAllowance is MTokenTransfer, MTokenAllowanceController, IERC20Allowance, IERC677Token { //////////////////////// // Mutable state //////////////////////// // `allowed` tracks rights to spends others tokens as per ERC20 // owner => spender => amount mapping (address => mapping (address => uint256)) private _allowed; //////////////////////// // Constructor //////////////////////// constructor() internal { } //////////////////////// // Public functions //////////////////////// // // Implements IERC20Token // /// @dev This function makes it easy to read the `allowed[]` map /// @param owner The address of the account that owns the token /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address owner, address spender) public constant returns (uint256 remaining) { uint256 override = mAllowanceOverride(owner, spender); if (override > 0) { return override; } return _allowed[owner][spender]; } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// where allowance per spender must be 0 to allow change of such allowance /// @param spender The address of the account able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True or reverts, False is never returned function approve(address spender, uint256 amount) public returns (bool success) { // Alerts the token controller of the approve function call require(mOnApprove(msg.sender, spender, amount)); // 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((amount == 0 || _allowed[msg.sender][spender] == 0) && mAllowanceOverride(msg.sender, spender) == 0); _allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param from The address holding the tokens being transferred /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return True if the transfer was successful, reverts in any other case function transferFrom(address from, address to, uint256 amount) public returns (bool success) { uint256 allowed = mAllowanceOverride(from, msg.sender); if (allowed == 0) { // The standard ERC 20 transferFrom functionality allowed = _allowed[from][msg.sender]; // yes this will underflow but then we'll revert. will cost gas however so don't underflow _allowed[from][msg.sender] -= amount; } require(allowed >= amount); mTransfer(from, to, amount); return true; } // // Implements IERC677Token // /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param spender The address of the contract able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True or reverts, False is never returned function approveAndCall( address spender, uint256 amount, bytes extraData ) public returns (bool success) { require(approve(spender, amount)); success = IERC677Callback(spender).receiveApproval( msg.sender, amount, this, extraData ); require(success); return true; } //////////////////////// // Internal functions //////////////////////// // // Implements default MTokenAllowanceController // // no override in default implementation function mAllowanceOverride( address /*owner*/, address /*spender*/ ) internal constant returns (uint256) { return 0; } } /// @title Reads and writes snapshots /// @dev Manages reading and writing a series of values, where each value has assigned a snapshot id for access to historical data /// @dev may be added to any contract to provide snapshotting mechanism. should be mixed in with any of MSnapshotPolicy implementations to customize snapshot creation mechanics /// observes MSnapshotPolicy /// based on MiniMe token contract Snapshot is MSnapshotPolicy { //////////////////////// // Types //////////////////////// /// @dev `Values` is the structure that attaches a snapshot id to a /// given value, the snapshot id attached is the one that last changed the /// value struct Values { // `snapshotId` is the snapshot id that the value was generated at uint256 snapshotId; // `value` at a specific snapshot id uint256 value; } //////////////////////// // Internal functions //////////////////////// function hasValue( Values[] storage values ) internal constant returns (bool) { return values.length > 0; } /// @dev makes sure that 'snapshotId' between current snapshot id (mCurrentSnapshotId) and first snapshot id. this guarantees that getValueAt returns value from one of the snapshots. function hasValueAt( Values[] storage values, uint256 snapshotId ) internal constant returns (bool) { require(snapshotId <= mCurrentSnapshotId()); return values.length > 0 && values[0].snapshotId <= snapshotId; } /// gets last value in the series function getValue( Values[] storage values, uint256 defaultValue ) internal constant returns (uint256) { if (values.length == 0) { return defaultValue; } else { uint256 last = values.length - 1; return values[last].value; } } /// @dev `getValueAt` retrieves value at a given snapshot id /// @param values The series of values being queried /// @param snapshotId Snapshot id to retrieve the value at /// @return Value in series being queried function getValueAt( Values[] storage values, uint256 snapshotId, uint256 defaultValue ) internal constant returns (uint256) { require(snapshotId <= mCurrentSnapshotId()); // Empty value if (values.length == 0) { return defaultValue; } // Shortcut for the out of bounds snapshots uint256 last = values.length - 1; uint256 lastSnapshot = values[last].snapshotId; if (snapshotId >= lastSnapshot) { return values[last].value; } uint256 firstSnapshot = values[0].snapshotId; if (snapshotId < firstSnapshot) { return defaultValue; } // Binary search of the value in the array uint256 min = 0; uint256 max = last; while (max > min) { uint256 mid = (max + min + 1) / 2; // must always return lower indice for approximate searches if (values[mid].snapshotId <= snapshotId) { min = mid; } else { max = mid - 1; } } return values[min].value; } /// @dev `setValue` used to update sequence at next snapshot /// @param values The sequence being updated /// @param value The new last value of sequence function setValue( Values[] storage values, uint256 value ) internal { // TODO: simplify or break into smaller functions uint256 currentSnapshotId = mAdvanceSnapshotId(); // Always create a new entry if there currently is no value bool empty = values.length == 0; if (empty) { // Create a new entry values.push( Values({ snapshotId: currentSnapshotId, value: value }) ); return; } uint256 last = values.length - 1; bool hasNewSnapshot = values[last].snapshotId < currentSnapshotId; if (hasNewSnapshot) { // Do nothing if the value was not modified bool unmodified = values[last].value == value; if (unmodified) { return; } // Create new entry values.push( Values({ snapshotId: currentSnapshotId, value: value }) ); } else { // We are updating the currentSnapshotId bool previousUnmodified = last > 0 && values[last - 1].value == value; if (previousUnmodified) { // Remove current snapshot if current value was set to previous value delete values[last]; values.length--; return; } // Overwrite next snapshot entry values[last].value = value; } } } /// @title access to snapshots of a token /// @notice allows to implement complex token holder rights like revenue disbursal or voting /// @notice snapshots are series of values with assigned ids. ids increase strictly. particular id mechanism is not assumed contract ITokenSnapshots { //////////////////////// // Public functions //////////////////////// /// @notice Total amount of tokens at a specific `snapshotId`. /// @param snapshotId of snapshot at which totalSupply is queried /// @return The total amount of tokens at `snapshotId` /// @dev reverts on snapshotIds greater than currentSnapshotId() /// @dev returns 0 for snapshotIds less than snapshotId of first value function totalSupplyAt(uint256 snapshotId) public constant returns(uint256); /// @dev Queries the balance of `owner` at a specific `snapshotId` /// @param owner The address from which the balance will be retrieved /// @param snapshotId of snapshot at which the balance is queried /// @return The balance at `snapshotId` function balanceOfAt(address owner, uint256 snapshotId) public constant returns (uint256); /// @notice upper bound of series of snapshotIds for which there's a value in series /// @return snapshotId function currentSnapshotId() public constant returns (uint256); } /// @title represents link between cloned and parent token /// @dev when token is clone from other token, initial balances of the cloned token /// correspond to balances of parent token at the moment of parent snapshot id specified /// @notice please note that other tokens beside snapshot token may be cloned contract IClonedTokenParent is ITokenSnapshots { //////////////////////// // Public functions //////////////////////// /// @return address of parent token, address(0) if root /// @dev parent token does not need to clonable, nor snapshottable, just a normal token function parentToken() public constant returns(IClonedTokenParent parent); /// @return snapshot at wchich initial token distribution was taken function parentSnapshotId() public constant returns(uint256 snapshotId); } /// @title token with snapshots and transfer functionality /// @dev observes MTokenTransferController interface /// observes ISnapshotToken interface /// implementes MTokenTransfer interface contract BasicSnapshotToken is MTokenTransfer, MTokenTransferController, IClonedTokenParent, IBasicToken, Snapshot { //////////////////////// // Immutable state //////////////////////// // `PARENT_TOKEN` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned IClonedTokenParent private PARENT_TOKEN; // `PARENT_SNAPSHOT_ID` is the snapshot id from the Parent Token that was // used to determine the initial distribution of the cloned token uint256 private PARENT_SNAPSHOT_ID; //////////////////////// // Mutable state //////////////////////// // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the snapshot id that the change // occurred is also included in the map mapping (address => Values[]) internal _balances; // Tracks the history of the `totalSupply` of the token Values[] internal _totalSupplyValues; //////////////////////// // Constructor //////////////////////// /// @notice Constructor to create snapshot token /// @param parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param parentSnapshotId at which snapshot id clone was created, set to 0 to clone at upper bound /// @dev please not that as long as cloned token does not overwrite value at current snapshot id, it will refer /// to parent token at which this snapshot still may change until snapshot id increases. for that time tokens are coupled /// this is prevented by parentSnapshotId value of parentToken.currentSnapshotId() - 1 being the maxiumum /// see SnapshotToken.js test to learn consequences coupling has. constructor( IClonedTokenParent parentToken, uint256 parentSnapshotId ) Snapshot() internal { PARENT_TOKEN = parentToken; if (parentToken == address(0)) { require(parentSnapshotId == 0); } else { if (parentSnapshotId == 0) { require(parentToken.currentSnapshotId() > 0); PARENT_SNAPSHOT_ID = parentToken.currentSnapshotId() - 1; } else { PARENT_SNAPSHOT_ID = parentSnapshotId; } } } //////////////////////// // Public functions //////////////////////// // // Implements IBasicToken // /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint256) { return totalSupplyAtInternal(mCurrentSnapshotId()); } /// @param owner The address that's balance is being requested /// @return The balance of `owner` at the current block function balanceOf(address owner) public constant returns (uint256 balance) { return balanceOfAtInternal(owner, mCurrentSnapshotId()); } /// @notice Send `amount` tokens to `to` from `msg.sender` /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return True if the transfer was successful, reverts in any other case function transfer(address to, uint256 amount) public returns (bool success) { mTransfer(msg.sender, to, amount); return true; } // // Implements ITokenSnapshots // function totalSupplyAt(uint256 snapshotId) public constant returns(uint256) { return totalSupplyAtInternal(snapshotId); } function balanceOfAt(address owner, uint256 snapshotId) public constant returns (uint256) { return balanceOfAtInternal(owner, snapshotId); } function currentSnapshotId() public constant returns (uint256) { return mCurrentSnapshotId(); } // // Implements IClonedTokenParent // function parentToken() public constant returns(IClonedTokenParent parent) { return PARENT_TOKEN; } /// @return snapshot at wchich initial token distribution was taken function parentSnapshotId() public constant returns(uint256 snapshotId) { return PARENT_SNAPSHOT_ID; } // // Other public functions // /// @notice gets all token balances of 'owner' /// @dev intended to be called via eth_call where gas limit is not an issue function allBalancesOf(address owner) external constant returns (uint256[2][]) { /* very nice and working implementation below, // copy to memory Values[] memory values = _balances[owner]; do assembly { // in memory structs have simple layout where every item occupies uint256 balances := values } while (false);*/ Values[] storage values = _balances[owner]; uint256[2][] memory balances = new uint256[2][](values.length); for(uint256 ii = 0; ii < values.length; ++ii) { balances[ii] = [values[ii].snapshotId, values[ii].value]; } return balances; } //////////////////////// // Internal functions //////////////////////// function totalSupplyAtInternal(uint256 snapshotId) internal constant returns(uint256) { Values[] storage values = _totalSupplyValues; // If there is a value, return it, reverts if value is in the future if (hasValueAt(values, snapshotId)) { return getValueAt(values, snapshotId, 0); } // Try parent contract at or before the fork if (address(PARENT_TOKEN) != 0) { uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID; return PARENT_TOKEN.totalSupplyAt(earlierSnapshotId); } // Default to an empty balance return 0; } // get balance at snapshot if with continuation in parent token function balanceOfAtInternal(address owner, uint256 snapshotId) internal constant returns (uint256) { Values[] storage values = _balances[owner]; // If there is a value, return it, reverts if value is in the future if (hasValueAt(values, snapshotId)) { return getValueAt(values, snapshotId, 0); } // Try parent contract at or before the fork if (PARENT_TOKEN != address(0)) { uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID; return PARENT_TOKEN.balanceOfAt(owner, earlierSnapshotId); } // Default to an empty balance return 0; } // // Implements MTokenTransfer // /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param from The address holding the tokens being transferred /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return True if the transfer was successful, reverts in any other case function mTransfer( address from, address to, uint256 amount ) internal { // never send to address 0 require(to != address(0)); // block transfers in clone that points to future/current snapshots of parent token require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId()); // Alerts the token controller of the transfer require(mOnTransfer(from, to, amount)); // If the amount being transfered is more than the balance of the // account the transfer reverts uint256 previousBalanceFrom = balanceOf(from); require(previousBalanceFrom >= amount); // First update the balance array with the new value for the address // sending the tokens uint256 newBalanceFrom = previousBalanceFrom - amount; setValue(_balances[from], newBalanceFrom); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOf(to); uint256 newBalanceTo = previousBalanceTo + amount; assert(newBalanceTo >= previousBalanceTo); // Check for overflow setValue(_balances[to], newBalanceTo); // An event to make the transfer easy to find on the blockchain emit Transfer(from, to, amount); } } /// @title token generation and destruction /// @dev internal interface providing token generation and destruction, see MintableSnapshotToken for implementation contract MTokenMint { //////////////////////// // Internal functions //////////////////////// /// @notice Generates `amount` tokens that are assigned to `owner` /// @param owner The address that will be assigned the new tokens /// @param amount The quantity of tokens generated /// @dev reverts if tokens could not be generated function mGenerateTokens(address owner, uint256 amount) internal; /// @notice Burns `amount` tokens from `owner` /// @param owner The address that will lose the tokens /// @param amount The quantity of tokens to burn /// @dev reverts if tokens could not be destroyed function mDestroyTokens(address owner, uint256 amount) internal; } /// @title basic snapshot token with facitilites to generate and destroy tokens /// @dev implementes MTokenMint, does not expose any public functions that create/destroy tokens contract MintableSnapshotToken is BasicSnapshotToken, MTokenMint { //////////////////////// // Constructor //////////////////////// /// @notice Constructor to create a MintableSnapshotToken /// @param parentToken Address of the parent token, set to 0x0 if it is a /// new token constructor( IClonedTokenParent parentToken, uint256 parentSnapshotId ) BasicSnapshotToken(parentToken, parentSnapshotId) internal {} /// @notice Generates `amount` tokens that are assigned to `owner` /// @param owner The address that will be assigned the new tokens /// @param amount The quantity of tokens generated function mGenerateTokens(address owner, uint256 amount) internal { // never create for address 0 require(owner != address(0)); // block changes in clone that points to future/current snapshots of patent token require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId()); uint256 curTotalSupply = totalSupply(); uint256 newTotalSupply = curTotalSupply + amount; require(newTotalSupply >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = balanceOf(owner); uint256 newBalanceTo = previousBalanceTo + amount; assert(newBalanceTo >= previousBalanceTo); // Check for overflow setValue(_totalSupplyValues, newTotalSupply); setValue(_balances[owner], newBalanceTo); emit Transfer(0, owner, amount); } /// @notice Burns `amount` tokens from `owner` /// @param owner The address that will lose the tokens /// @param amount The quantity of tokens to burn function mDestroyTokens(address owner, uint256 amount) internal { // block changes in clone that points to future/current snapshots of patent token require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId()); uint256 curTotalSupply = totalSupply(); require(curTotalSupply >= amount); uint256 previousBalanceFrom = balanceOf(owner); require(previousBalanceFrom >= amount); uint256 newTotalSupply = curTotalSupply - amount; uint256 newBalanceFrom = previousBalanceFrom - amount; setValue(_totalSupplyValues, newTotalSupply); setValue(_balances[owner], newBalanceFrom); emit Transfer(owner, 0, amount); } } /* Copyright 2016, Jordi Baylina Copyright 2017, Remco Bloemen, Marcin Rudolf 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/>. */ /// @title StandardSnapshotToken Contract /// @author Jordi Baylina, Remco Bloemen, Marcin Rudolf /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev Various contracts are composed to provide required functionality of this token, different compositions are possible /// MintableSnapshotToken provides transfer, miniting and snapshotting functions /// TokenAllowance provides approve/transferFrom functions /// TokenMetadata adds name, symbol and other token metadata /// @dev This token is still abstract, Snapshot, BasicSnapshotToken and TokenAllowance observe interfaces that must be implemented /// MSnapshotPolicy - particular snapshot id creation mechanism /// MTokenController - controlls approvals and transfers /// see Neumark as an example /// @dev implements ERC223 token transfer contract StandardSnapshotToken is MintableSnapshotToken, TokenAllowance { //////////////////////// // Constructor //////////////////////// /// @notice Constructor to create a MiniMeToken /// is a new token /// param tokenName Name of the new token /// param decimalUnits Number of decimals of the new token /// param tokenSymbol Token Symbol for the new token constructor( IClonedTokenParent parentToken, uint256 parentSnapshotId ) MintableSnapshotToken(parentToken, parentSnapshotId) TokenAllowance() internal {} } /// @title old ERC223 callback function /// @dev as used in Neumark and ICBMEtherToken contract IERC223LegacyCallback { //////////////////////// // Public functions //////////////////////// function onTokenTransfer(address from, uint256 amount, bytes data) public; } contract IERC223Token is IERC20Token, ITokenMetadata { /// @dev Departure: We do not log data, it has no advantage over a standard /// log event. By sticking to the standard log event we /// stay compatible with constracts that expect and ERC20 token. // event Transfer( // address indexed from, // address indexed to, // uint256 amount, // bytes data); /// @dev Departure: We do not use the callback on regular transfer calls to /// stay compatible with constracts that expect and ERC20 token. // function transfer(address to, uint256 amount) // public // returns (bool); //////////////////////// // Public functions //////////////////////// function transfer(address to, uint256 amount, bytes data) public returns (bool); } contract Neumark is AccessControlled, AccessRoles, Agreement, DailyAndSnapshotable, StandardSnapshotToken, TokenMetadata, IERC223Token, NeumarkIssuanceCurve, Reclaimable, IsContract { //////////////////////// // Constants //////////////////////// string private constant TOKEN_NAME = "Neumark"; uint8 private constant TOKEN_DECIMALS = 18; string private constant TOKEN_SYMBOL = "NEU"; string private constant VERSION = "NMK_1.0"; //////////////////////// // Mutable state //////////////////////// // disable transfers when Neumark is created bool private _transferEnabled = false; // at which point on curve new Neumarks will be created, see NeumarkIssuanceCurve contract // do not use to get total invested funds. see burn(). this is just a cache for expensive inverse function uint256 private _totalEurUlps; //////////////////////// // Events //////////////////////// event LogNeumarksIssued( address indexed owner, uint256 euroUlps, uint256 neumarkUlps ); event LogNeumarksBurned( address indexed owner, uint256 euroUlps, uint256 neumarkUlps ); //////////////////////// // Constructor //////////////////////// constructor( IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter ) AccessRoles() Agreement(accessPolicy, forkArbiter) StandardSnapshotToken( IClonedTokenParent(0x0), 0 ) TokenMetadata( TOKEN_NAME, TOKEN_DECIMALS, TOKEN_SYMBOL, VERSION ) DailyAndSnapshotable(0) NeumarkIssuanceCurve() Reclaimable() public {} //////////////////////// // Public functions //////////////////////// /// @notice issues new Neumarks to msg.sender with reward at current curve position /// moves curve position by euroUlps /// callable only by ROLE_NEUMARK_ISSUER function issueForEuro(uint256 euroUlps) public only(ROLE_NEUMARK_ISSUER) acceptAgreement(msg.sender) returns (uint256) { require(_totalEurUlps + euroUlps >= _totalEurUlps); uint256 neumarkUlps = incremental(_totalEurUlps, euroUlps); _totalEurUlps += euroUlps; mGenerateTokens(msg.sender, neumarkUlps); emit LogNeumarksIssued(msg.sender, euroUlps, neumarkUlps); return neumarkUlps; } /// @notice used by ROLE_NEUMARK_ISSUER to transer newly issued neumarks /// typically to the investor and platform operator function distribute(address to, uint256 neumarkUlps) public only(ROLE_NEUMARK_ISSUER) acceptAgreement(to) { mTransfer(msg.sender, to, neumarkUlps); } /// @notice msg.sender can burn their Neumarks, curve is rolled back using inverse /// curve. as a result cost of Neumark gets lower (reward is higher) function burn(uint256 neumarkUlps) public only(ROLE_NEUMARK_BURNER) { burnPrivate(neumarkUlps, 0, _totalEurUlps); } /// @notice executes as function above but allows to provide search range for low gas burning function burn(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) public only(ROLE_NEUMARK_BURNER) { burnPrivate(neumarkUlps, minEurUlps, maxEurUlps); } function enableTransfer(bool enabled) public only(ROLE_TRANSFER_ADMIN) { _transferEnabled = enabled; } function createSnapshot() public only(ROLE_SNAPSHOT_CREATOR) returns (uint256) { return DailyAndSnapshotable.createSnapshot(); } function transferEnabled() public constant returns (bool) { return _transferEnabled; } function totalEuroUlps() public constant returns (uint256) { return _totalEurUlps; } function incremental(uint256 euroUlps) public constant returns (uint256 neumarkUlps) { return incremental(_totalEurUlps, euroUlps); } // // Implements IERC223Token with IERC223Callback (onTokenTransfer) callback // // old implementation of ERC223 that was actual when ICBM was deployed // as Neumark is already deployed this function keeps old behavior for testing function transfer(address to, uint256 amount, bytes data) public returns (bool) { // it is necessary to point out implementation to be called BasicSnapshotToken.mTransfer(msg.sender, to, amount); // Notify the receiving contract. if (isContract(to)) { IERC223LegacyCallback(to).onTokenTransfer(msg.sender, amount, data); } return true; } //////////////////////// // Internal functions //////////////////////// // // Implements MTokenController // function mOnTransfer( address from, address, // to uint256 // amount ) internal acceptAgreement(from) returns (bool allow) { // must have transfer enabled or msg.sender is Neumark issuer return _transferEnabled || accessPolicy().allowed(msg.sender, ROLE_NEUMARK_ISSUER, this, msg.sig); } function mOnApprove( address owner, address, // spender, uint256 // amount ) internal acceptAgreement(owner) returns (bool allow) { return true; } //////////////////////// // Private functions //////////////////////// function burnPrivate(uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) private { uint256 prevEuroUlps = _totalEurUlps; // burn first in the token to make sure balance/totalSupply is not crossed mDestroyTokens(msg.sender, burnNeumarkUlps); _totalEurUlps = cumulativeInverse(totalSupply(), minEurUlps, maxEurUlps); // actually may overflow on non-monotonic inverse assert(prevEuroUlps >= _totalEurUlps); uint256 euroUlps = prevEuroUlps - _totalEurUlps; emit LogNeumarksBurned(msg.sender, euroUlps, burnNeumarkUlps); } } /// @title uniquely identifies deployable (non-abstract) platform contract /// @notice cheap way of assigning implementations to knownInterfaces which represent system services /// unfortunatelly ERC165 does not include full public interface (ABI) and does not provide way to list implemented interfaces /// EIP820 still in the making /// @dev ids are generated as follows keccak256("neufund-platform:<contract name>") /// ids roughly correspond to ABIs contract IContractId { /// @param id defined as above /// @param version implementation version function contractId() public pure returns (bytes32 id, uint256 version); } /// @title current ERC223 fallback function /// @dev to be used in all future token contract /// @dev NEU and ICBMEtherToken (obsolete) are the only contracts that still uses IERC223LegacyCallback contract IERC223Callback { //////////////////////// // Public functions //////////////////////// function tokenFallback(address from, uint256 amount, bytes data) public; } /// @title disburse payment token amount to snapshot token holders /// @dev payment token received via ERC223 Transfer contract IFeeDisbursal is IERC223Callback { // TODO: declare interface } /// @title disburse payment token amount to snapshot token holders /// @dev payment token received via ERC223 Transfer contract IPlatformPortfolio is IERC223Callback { // TODO: declare interface } contract ITokenExchangeRateOracle { /// @notice provides actual price of 'numeratorToken' in 'denominatorToken' /// returns timestamp at which price was obtained in oracle function getExchangeRate(address numeratorToken, address denominatorToken) public constant returns (uint256 rateFraction, uint256 timestamp); /// @notice allows to retreive multiple exchange rates in once call function getExchangeRates(address[] numeratorTokens, address[] denominatorTokens) public constant returns (uint256[] rateFractions, uint256[] timestamps); } /// @title root of trust and singletons + known interface registry /// provides a root which holds all interfaces platform trust, this includes /// singletons - for which accessors are provided /// collections of known instances of interfaces /// @dev interfaces are identified by bytes4, see KnownInterfaces.sol contract Universe is Agreement, IContractId, KnownInterfaces { //////////////////////// // Events //////////////////////// /// raised on any change of singleton instance /// @dev for convenience we provide previous instance of singleton in replacedInstance event LogSetSingleton( bytes4 interfaceId, address instance, address replacedInstance ); /// raised on add/remove interface instance in collection event LogSetCollectionInterface( bytes4 interfaceId, address instance, bool isSet ); //////////////////////// // Mutable state //////////////////////// // mapping of known contracts to addresses of singletons mapping(bytes4 => address) private _singletons; // mapping of known interfaces to collections of contracts mapping(bytes4 => mapping(address => bool)) private _collections; // solium-disable-line indentation // known instances mapping(address => bytes4[]) private _instances; //////////////////////// // Constructor //////////////////////// constructor( IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter ) Agreement(accessPolicy, forkArbiter) public { setSingletonPrivate(KNOWN_INTERFACE_ACCESS_POLICY, accessPolicy); setSingletonPrivate(KNOWN_INTERFACE_FORK_ARBITER, forkArbiter); } //////////////////////// // Public methods //////////////////////// /// get singleton instance for 'interfaceId' function getSingleton(bytes4 interfaceId) public constant returns (address) { return _singletons[interfaceId]; } function getManySingletons(bytes4[] interfaceIds) public constant returns (address[]) { address[] memory addresses = new address[](interfaceIds.length); uint256 idx; while(idx < interfaceIds.length) { addresses[idx] = _singletons[interfaceIds[idx]]; idx += 1; } return addresses; } /// checks of 'instance' is instance of interface 'interfaceId' function isSingleton(bytes4 interfaceId, address instance) public constant returns (bool) { return _singletons[interfaceId] == instance; } /// checks if 'instance' is one of instances of 'interfaceId' function isInterfaceCollectionInstance(bytes4 interfaceId, address instance) public constant returns (bool) { return _collections[interfaceId][instance]; } function isAnyOfInterfaceCollectionInstance(bytes4[] interfaceIds, address instance) public constant returns (bool) { uint256 idx; while(idx < interfaceIds.length) { if (_collections[interfaceIds[idx]][instance]) { return true; } idx += 1; } return false; } /// gets all interfaces of given instance function getInterfacesOfInstance(address instance) public constant returns (bytes4[] interfaces) { return _instances[instance]; } /// sets 'instance' of singleton with interface 'interfaceId' function setSingleton(bytes4 interfaceId, address instance) public only(ROLE_UNIVERSE_MANAGER) { setSingletonPrivate(interfaceId, instance); } /// convenience method for setting many singleton instances function setManySingletons(bytes4[] interfaceIds, address[] instances) public only(ROLE_UNIVERSE_MANAGER) { require(interfaceIds.length == instances.length); uint256 idx; while(idx < interfaceIds.length) { setSingletonPrivate(interfaceIds[idx], instances[idx]); idx += 1; } } /// set or unset 'instance' with 'interfaceId' in collection of instances function setCollectionInterface(bytes4 interfaceId, address instance, bool set) public only(ROLE_UNIVERSE_MANAGER) { setCollectionPrivate(interfaceId, instance, set); } /// set or unset 'instance' in many collections of instances function setInterfaceInManyCollections(bytes4[] interfaceIds, address instance, bool set) public only(ROLE_UNIVERSE_MANAGER) { uint256 idx; while(idx < interfaceIds.length) { setCollectionPrivate(interfaceIds[idx], instance, set); idx += 1; } } /// set or unset array of collection function setCollectionsInterfaces(bytes4[] interfaceIds, address[] instances, bool[] set_flags) public only(ROLE_UNIVERSE_MANAGER) { require(interfaceIds.length == instances.length); require(interfaceIds.length == set_flags.length); uint256 idx; while(idx < interfaceIds.length) { setCollectionPrivate(interfaceIds[idx], instances[idx], set_flags[idx]); idx += 1; } } // // Implements IContractId // function contractId() public pure returns (bytes32 id, uint256 version) { return (0x8b57bfe21a3ef4854e19d702063b6cea03fa514162f8ff43fde551f06372fefd, 0); } //////////////////////// // Getters //////////////////////// function accessPolicy() public constant returns (IAccessPolicy) { return IAccessPolicy(_singletons[KNOWN_INTERFACE_ACCESS_POLICY]); } function forkArbiter() public constant returns (IEthereumForkArbiter) { return IEthereumForkArbiter(_singletons[KNOWN_INTERFACE_FORK_ARBITER]); } function neumark() public constant returns (Neumark) { return Neumark(_singletons[KNOWN_INTERFACE_NEUMARK]); } function etherToken() public constant returns (IERC223Token) { return IERC223Token(_singletons[KNOWN_INTERFACE_ETHER_TOKEN]); } function euroToken() public constant returns (IERC223Token) { return IERC223Token(_singletons[KNOWN_INTERFACE_EURO_TOKEN]); } function etherLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_ETHER_LOCK]; } function euroLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_EURO_LOCK]; } function icbmEtherLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_ICBM_ETHER_LOCK]; } function icbmEuroLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_ICBM_EURO_LOCK]; } function identityRegistry() public constant returns (address) { return IIdentityRegistry(_singletons[KNOWN_INTERFACE_IDENTITY_REGISTRY]); } function tokenExchangeRateOracle() public constant returns (address) { return ITokenExchangeRateOracle(_singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE]); } function feeDisbursal() public constant returns (address) { return IFeeDisbursal(_singletons[KNOWN_INTERFACE_FEE_DISBURSAL]); } function platformPortfolio() public constant returns (address) { return IPlatformPortfolio(_singletons[KNOWN_INTERFACE_PLATFORM_PORTFOLIO]); } function tokenExchange() public constant returns (address) { return _singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE]; } function gasExchange() public constant returns (address) { return _singletons[KNOWN_INTERFACE_GAS_EXCHANGE]; } function platformTerms() public constant returns (address) { return _singletons[KNOWN_INTERFACE_PLATFORM_TERMS]; } //////////////////////// // Private methods //////////////////////// function setSingletonPrivate(bytes4 interfaceId, address instance) private { require(interfaceId != KNOWN_INTERFACE_UNIVERSE, "NF_UNI_NO_UNIVERSE_SINGLETON"); address replacedInstance = _singletons[interfaceId]; // do nothing if not changing if (replacedInstance != instance) { dropInstance(replacedInstance, interfaceId); addInstance(instance, interfaceId); _singletons[interfaceId] = instance; } emit LogSetSingleton(interfaceId, instance, replacedInstance); } function setCollectionPrivate(bytes4 interfaceId, address instance, bool set) private { // do nothing if not changing if (_collections[interfaceId][instance] == set) { return; } _collections[interfaceId][instance] = set; if (set) { addInstance(instance, interfaceId); } else { dropInstance(instance, interfaceId); } emit LogSetCollectionInterface(interfaceId, instance, set); } function addInstance(address instance, bytes4 interfaceId) private { if (instance == address(0)) { // do not add null instance return; } bytes4[] storage current = _instances[instance]; uint256 idx; while(idx < current.length) { // instancy has this interface already, do nothing if (current[idx] == interfaceId) return; idx += 1; } // new interface current.push(interfaceId); } function dropInstance(address instance, bytes4 interfaceId) private { if (instance == address(0)) { // do not drop null instance return; } bytes4[] storage current = _instances[instance]; uint256 idx; uint256 last = current.length - 1; while(idx <= last) { if (current[idx] == interfaceId) { // delete element if (idx < last) { // if not last element move last element to idx being deleted current[idx] = current[last]; } // delete last element current.length -= 1; return; } idx += 1; } } }
msg.sender can burn their Neumarks, curve is rolled back using inverse curve. as a result cost of Neumark gets lower (reward is higher)
function burn(uint256 neumarkUlps) public only(ROLE_NEUMARK_BURNER) { burnPrivate(neumarkUlps, 0, _totalEurUlps); }
1,800,971
./full_match/80001/0xa31bE037b32882131b6FC0AD292e094276d58Ce0/sources/_thirdweb-dev/contracts/extension/DelayedReveal.sol
Returns the decrypted i.e. revealed URI for a batch of tokens.
function getRevealURI(uint256 _batchId, bytes calldata _key) public view returns (string memory revealedURI) { bytes memory encryptedURI = encryptedBaseURI[_batchId]; if (encryptedURI.length == 0) { revert("Nothing to reveal"); } revealedURI = string(encryptDecrypt(encryptedURI, _key)); }
5,565,466
./full_match/5/0xEf8F1fe8918eB5BB70853F2dF2cAC85626d6FB56/sources/project_/contracts/base/modules/MintingReward.sol
Return the token supply - to be implemented (by override) in the child contract./
function _totalSupply() internal view virtual returns (uint256) {}
7,035,577
pragma solidity ^0.6.12; import { ERC20PausableUpgradeSafe, IERC20, SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import { SafeERC20 } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import {AddressArrayUtils} from "./library/AddressArrayUtils.sol"; import {ILimaSwap} from "./interfaces/ILimaSwap.sol"; import {ILimaToken} from "./interfaces/ILimaToken.sol"; import {LimaTokenStorage} from "./LimaTokenStorage.sol"; import {AmunUsers} from "./limaTokenModules/AmunUsers.sol"; import {InvestmentToken} from "./limaTokenModules/InvestmentToken.sol"; /** * @title LimaToken * @author Lima Protocol * * Standard LimaToken. */ contract LimaTokenHelper is LimaTokenStorage, InvestmentToken, AmunUsers { using AddressArrayUtils for address[]; using SafeMath for uint256; using SafeERC20 for IERC20; function initialize( address _limaSwap, address _feeWallet, address _currentUnderlyingToken, address[] memory _underlyingTokens, uint256 _mintFee, uint256 _burnFee, uint256 _performanceFee ) public initializer { __LimaTokenStorage_init_unchained( _limaSwap, _feeWallet, _currentUnderlyingToken, _underlyingTokens, _mintFee, _burnFee, _performanceFee ); __AmunUsers_init_unchained(true); } /* ============ View ============ */ /** * @dev Get total net token value. */ function getNetTokenValue(address _targetToken) public view returns (uint256 netTokenValue) { return getExpectedReturn( currentUnderlyingToken, _targetToken, getUnderlyingTokenBalance() ); } /** * @dev Get total net token value. */ function getNetTokenValueOf(address _targetToken, uint256 _amount) public view returns (uint256 netTokenValue) { return getExpectedReturn( currentUnderlyingToken, _targetToken, getUnderlyingTokenBalanceOf(_amount) ); } //helper for redirect to LimaSwap function getExpectedReturn( address _from, address _to, uint256 _amount ) public view returns (uint256 returnAmount) { returnAmount = limaSwap.getExpectedReturn(_from, _to, _amount); } function getUnderlyingTokenBalance() public view returns (uint256 balance) { return IERC20(currentUnderlyingToken).balanceOf(limaToken); } function getUnderlyingTokenBalanceOf(uint256 _amount) public view returns (uint256 balanceOf) { uint256 balance = getUnderlyingTokenBalance(); require(balance != 0, "LM4"); //"Balance of underlyng token cant be zero." return balance.mul(_amount).div(ILimaToken(limaToken).totalSupply()); } /** * @dev Return the performance over the last time interval */ function getPerformanceFee() public view returns (uint256 performanceFeeToWallet) { performanceFeeToWallet = 0; if ( ILimaToken(limaToken).getUnderlyingTokenBalanceOf(1000 ether) > lastUnderlyingBalancePer1000 && performanceFee != 0 ) { performanceFeeToWallet = ( ILimaToken(limaToken).getUnderlyingTokenBalance().sub( ILimaToken(limaToken) .totalSupply() .mul(lastUnderlyingBalancePer1000) .div(1000 ether) ) ) .div(performanceFee); } } /* ============ User ============ */ function getFee(uint256 _amount, uint256 _fee) public pure returns (uint256 feeAmount) { //get fee if (_fee > 0) { return _amount.div(_fee); } return 0; } /** * @dev Gets the expecterd return of a redeem */ function getExpectedReturnRedeem(address _to, uint256 _amount) external view returns (uint256 minimumReturn) { _amount = getUnderlyingTokenBalanceOf(_amount); _amount = _amount.sub(getFee(_amount, burnFee)); return getExpectedReturn(currentUnderlyingToken, _to, _amount); } /** * @dev Gets the expecterd return of a create */ function getExpectedReturnCreate(address _from, uint256 _amount) external view returns (uint256 minimumReturn) { _amount = _amount.sub(getFee(_amount, mintFee)); return getExpectedReturn(_from, currentUnderlyingToken, _amount); } /** * @dev Gets the expected returns of a rebalance */ function getExpectedReturnRebalance( address _bestToken ) external view returns (uint256 minimumReturnGov) { address _govToken = limaSwap.getGovernanceToken(currentUnderlyingToken); minimumReturnGov = getExpectedReturn( _govToken, _bestToken, IERC20(_govToken).balanceOf(limaToken) ); return (minimumReturnGov); } function getGovernanceToken() external view returns (address token) { return limaSwap.getGovernanceToken(currentUnderlyingToken); } }
Gets the expecterd return of a redeem/
function getExpectedReturnRedeem(address _to, uint256 _amount) external view returns (uint256 minimumReturn) { _amount = getUnderlyingTokenBalanceOf(_amount); _amount = _amount.sub(getFee(_amount, burnFee)); return getExpectedReturn(currentUnderlyingToken, _to, _amount); }
6,342,974
./partial_match/3/0xa54B20de67B059944c0eeD388e71f4D1a9e14041/sources/RigelGift.sol
user claims reward Eligible to earn referral spins only upto specified limit
function claimAndAddReferralSpin( uint256 projectID, uint8 tickerNum, address linkCreator ) external onlyActiveProject(projectID) { claimReward(projectID, tickerNum); require( linkCreator != _msgSender(), "RigelGift: Cannot Use referral link to self" ); if (linkCreator != address(0)) { UserClaimData memory claim = projectClaims[projectID][linkCreator]; if (claim.rSpinAvlb + 1 <= _maxReferralSpins) { claim.rSpinAvlb = claim.rSpinAvlb.add(1); projectClaims[projectID][linkCreator] = claim; emit SpinEarned(projectID, linkCreator, _msgSender()); } } }
5,272,840
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.4.22 <0.9.0; import "remix_tests.sol"; // this import is automatically injected by Remix. import "remix_accounts.sol"; import "./PROJECT_XXX.sol"; // File name has to end with '_test.sol', this file can contain more than one testSuite contracts contract testSuite { Mooney MyMoon; /// 'beforeAll' runs before all other tests /// More special functions are: 'beforeEach', 'beforeAll', 'afterEach' & 'afterAll' function beforeAll() public { MyMoon = new Mooney(); } function checkCorrectTotalSupply() public { Assert.equal(MyMoon.totalSupply(), uint256(45000000000000000), "2 should be equal to 2"); } function checkGetFraction() public { Assert.equal(MyMoon.getFraction(3,100), 3, "2 should be equal to 2"); } function checkCorrectTaxableThresholds() public { //taxableThresholds[0] = [3000, 0]; //taxableThresholds[1] = [5000, 200]; //taxableThresholds[2] = [6000, 300]; uint256[] memory result = MyMoon.determineTax(5); Assert.equal(result[0], uint256(5), "threshold 1 - full amount - does not equal 5"); Assert.equal(result[1], uint256(0), "threshold 1 - tax amount - does not equal 0"); uint256[] memory result2 = MyMoon.determineTax(3500); Assert.equal(result2[0], uint256(3300), "threshold 1 - full amount - does not equal 5"); Assert.equal(result2[1], uint256(200), "threshold 1 - tax amount - does not equal 5"); uint256[] memory result3 = MyMoon.determineTax(5500); Assert.equal(result3[0], uint256(5200), "threshold 1 - full amount - does not equal 5"); Assert.equal(result3[1], uint256(300), "threshold 1 - tax amount - does not equal 5"); } function checkSuccess2() public pure returns (bool) { // Use the return value (true or false) to test the contract return true; } function checkFailure() public { Assert.equal(uint(1), uint(2), "1 is not equal to 2"); } /// Custom Transaction Context /// See more: https://remix-ide.readthedocs.io/en/latest/unittesting.html#customization /// #sender: account-1 /// #value: 100 function checkSenderAndValue() public payable { // account index varies 0-9, value is in wei Assert.equal(msg.sender, TestsAccounts.getAccount(1), "Invalid sender"); Assert.equal(msg.value, 100, "Invalid value"); } }
'beforeAll' runs before all other tests More special functions are: 'beforeEach', 'beforeAll', 'afterEach' & 'afterAll'
function beforeAll() public { MyMoon = new Mooney(); }
15,782,651
/** * * ORACLIZE_API * * Copyright (c) 2015-2016 Oraclize SRL * Copyright (c) 2016 Oraclize LTD * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ pragma solidity >= 0.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI! /** * * @notice The following is a dummy contract that is only used to emit a * notification to the end-user they are using wrong solidity * compiler version. * */ contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external; } contract OraclizeI { address public cbAddress; mapping (bytes32 => uint256) public price; mapping (address => address) public addressCustomPaymentToken; function unsetCustomTokenPayment() external; function convertToERC20Price( uint256 _queryPriceInWei, address _tokenAddress ) public view returns(uint256 _price); function queryCached() payable external returns (bytes32 _queryId); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function setProofType( byte _proofType ) external; function setCustomGasPrice( uint256 _gasPrice ) external; function requestQueryCaching( bytes32 _queryId ) external; function setCustomTokenPayment( address _tokenAddress ) external; function getPrice( bytes1 _datasource ) public view returns (uint256 _dsprice); function getPrice( string memory _datasource ) public view returns (uint256 _dsprice); function getPrice( bytes1 _datasource, address _contractToQuery ) public view returns (uint256 _dsprice); function getPrice( bytes1 _datasource, uint256 _gasLimit ) public view returns (uint256 _dsprice); function getPrice( string memory _datasource, address _contractToQuery ) public view returns (uint256 _dsprice); function getPrice( string memory _datasource, uint256 _gasLimit ) public view returns (uint256 _dsprice); function requestCallbackRebroadcast( bytes32 _queryId, uint256 _gasLimit, uint256 _gasPrice ) payable external; function queryN( uint256 _timestamp, bytes1 _datasource, bytes memory _argN ) public payable returns (bytes32 _id); function getPrice( bytes1 _datasource, uint256 _gasLimit, address _contractToQuery ) public view returns (uint256 _dsprice); function getRebroadcastCost( uint256 _gasLimit, uint256 _gasPrice ) public pure returns (uint256 _rebroadcastCost); function query( uint256 _timestamp, bytes1 _datasource, string calldata _arg ) external payable returns (bytes32 _id); function queryN( uint256 _timestamp, string memory _datasource, bytes memory _argN ) public payable returns (bytes32 _id); function getPrice( string memory _datasource, uint256 _gasLimit, address _contractToQuery ) public view returns (uint256 _dsprice); function query( uint256 _timestamp, string calldata _datasource, string calldata _arg ) external payable returns (bytes32 _id); function query2( uint256 _timestamp, bytes1 _datasource, string memory _arg1, string memory _arg2 ) public payable returns (bytes32 _id); function query2( uint256 _timestamp, string memory _datasource, string memory _arg1, string memory _arg2 ) public payable returns (bytes32 _id); function query_withGasLimit( uint256 _timestamp, bytes1 _datasource, string calldata _arg, uint256 _gasLimit ) external payable returns (bytes32 _id); function queryN_withGasLimit( uint256 _timestamp, bytes1 _datasource, bytes calldata _argN, uint256 _gasLimit ) external payable returns (bytes32 _id); function query_withGasLimit( uint256 _timestamp, string calldata _datasource, string calldata _arg, uint256 _gasLimit ) external payable returns (bytes32 _id); function queryN_withGasLimit( uint256 _timestamp, string calldata _datasource, bytes calldata _argN, uint256 _gasLimit ) external payable returns (bytes32 _id); function query2_withGasLimit( uint256 _timestamp, bytes1 _datasource, string calldata _arg1, string calldata _arg2, uint256 _gasLimit ) external payable returns (bytes32 _id); function query2_withGasLimit( uint256 _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint256 _gasLimit ) external payable returns (bytes32 _id); } interface ERC20Interface { event Transfer( address indexed _from, address indexed _to, uint256 tokens ); event Approval( address indexed _tokenOwner, address indexed _spender, uint256 tokens ); function totalSupply() external view returns (uint256); function transfer( address _to, uint256 _tokens ) external returns (bool _success); function balanceOf( address _tokenOwner ) external view returns (uint256 _balance); function approve( address _tokenSpender, uint256 _tokenAmount ) external returns (bool); function transferFrom( address _from, address _to, uint256 _tokens ) external returns (bool _success); function allowance( address _tokenOwner, address _spender ) external view returns (uint256 _remaining); } contract OraclizeAddrResolverI { function getAddress() public returns (address _address); } /** * * Begin solidity-cborutils * * https://github.com/smartcontractkit/solidity-cborutils * * MIT License * * Copyright (c) 2018 SmartContract ChainLink, Ltd. * * 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. * */ library Buffer { struct buffer { bytes buf; uint256 capacity; } function init(buffer memory _buf, uint256 _capacity) internal pure { uint256 capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint256 _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint256 _a, uint256 _b) private pure returns (uint256 _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append( buffer memory _buf, bytes memory _data ) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint256 dest; uint256 src; uint256 len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function appendInt( buffer memory _buf, uint256 _data, uint256 _len ) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint256 mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType( Buffer.buffer memory _buf, uint8 _major, uint256 _value ) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType( Buffer.buffer memory _buf, uint8 _major ) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt( Buffer.buffer memory _buf, uint256 _value ) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt( Buffer.buffer memory _buf, int _value ) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint256(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint256(-1 - _value)); } } function encodeBytes( Buffer.buffer memory _buf, bytes memory _value ) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString( Buffer.buffer memory _buf, string memory _value ) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray( Buffer.buffer memory _buf ) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /** * * End solidity-cborutils * */ contract usingOraclize { using CBOR for Buffer.buffer; OraclizeI oraclize; OraclizeAddrResolverI OAR; uint256 constant day = 60 * 60 * 24; uint256 constant week = 60 * 60 * 24 * 7; uint256 constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string oraclize_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; modifier oraclizeAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { oraclize_setNetwork(networkID_auto); } address oraclizeConnector = OAR.getAddress(); if (address(oraclize) != oraclizeConnector) { oraclize = OraclizeI(oraclizeConnector); } _; } modifier oraclize_randomDS_proofVerify ( bytes32 _queryId, string memory _result, bytes memory _proof ) { // Note: RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require( (_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1)) ); bool proofVerified = oraclize_randomDS_proofVerify__main( _proof, _queryId, bytes(_result), oraclize_getNetworkName() ); require(proofVerified); _; } function oraclize_setNetwork( uint8 _networkID ) internal returns (bool _networkSet) { _networkID; // NOTE: Silence the warning and remain backwards compatible return oraclize_setNetwork(); } function oraclize_setNetworkName( string memory _network_name ) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string memory _networkName) { return oraclize_network_name; } function oraclize_setNetwork() internal returns (bool _networkSet) { // Note: Mainnet... if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } // Note: Ropsten testnet... if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } // Note: Kovan testnet... if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } // Note: Rinkeby testnet... if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } // Note: Goerli testnet... if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); oraclize_setNetworkName("eth_goerli"); return true; } // Note: Ethereum-bridge testnet... if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } // Note: Ether.camp ide... if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } // Note: Browser-solidity... if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } /** * @dev The following `__callback` functions are just placeholders ideally * meant to be defined in child contract when proofs are used. * The function bodies simply silence compiler warnings. */ function __callback( bytes32 _myid, string memory _result ) public { __callback(_myid, _result, new bytes(0)); } function __callback( bytes32 _myid, string memory _result, bytes memory _proof ) public { _myid; _result; _proof; oraclize_randomDS_args[bytes32(0)] = bytes32(0); } /** * * @notice oraclize_getPrice(...) overloads follow... * */ function oraclize_getPrice( string memory _datasource ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice( byte _datasource ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice( string memory _datasource, uint256 _gasLimit ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_getPrice( byte _datasource, uint256 _gasLimit ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_getPrice( string memory _datasource, address _contractToQuery ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.getPrice(_datasource, _contractToQuery); } function oraclize_getPrice( byte _datasource, address _contractToQuery ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.getPrice(_datasource, _contractToQuery); } function oraclize_getPrice( string memory _datasource, address _contractToQuery, uint256 _gasLimit ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit, _contractToQuery); } function oraclize_getPrice( byte _datasource, address _contractToQuery, uint256 _gasLimit ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit, _contractToQuery); } function oraclize_getPrice( byte _datasource, uint256 _gasLimit, uint256 _gasPrice ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, proofType_NONE ) ) ); return _queryPrice += _gasLimit * _gasPrice; } function oraclize_getPrice( byte _datasource, uint256 _gasLimit, uint256 _gasPrice, byte _proofType ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, _proofType ) ) ); return _queryPrice += _gasLimit * _gasPrice; } function oraclize_getPrice( string memory _datasource, uint256 _gasLimit, uint256 _gasPrice ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, proofType_NONE ) ) ); return _queryPrice += _gasLimit * _gasPrice; } function oraclize_getPrice( string memory _datasource, uint256 _gasLimit, uint256 _gasPrice, byte _proofType ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, _proofType ) ) ); return _queryPrice += _gasLimit * _gasPrice; } /** * * @notice oraclize_getPriceERC20(...) overloads follow... * */ function oraclize_getPriceERC20( string memory _datasource ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource), oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( byte _datasource ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource), oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( address _tokenAddress, string memory _datasource ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource), _tokenAddress ); } function oraclize_getPriceERC20( address _tokenAddress, byte _datasource ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource), _tokenAddress ); } function oraclize_getPriceERC20( string memory _datasource, uint256 _gasLimit ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _gasLimit), oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( byte _datasource, uint256 _gasLimit ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _gasLimit), oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( string memory _datasource, uint256 _gasLimit, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _gasLimit), _tokenAddress ); } function oraclize_getPriceERC20( byte _datasource, uint256 _gasLimit, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _gasLimit), _tokenAddress ); } function oraclize_getPriceERC20( string memory _datasource, address _contractToQuery ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _contractToQuery), oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( byte _datasource, address _contractToQuery ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _contractToQuery), oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( string memory _datasource, address _contractToQuery, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _contractToQuery), _tokenAddress ); } function oraclize_getPriceERC20( byte _datasource, address _contractToQuery, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _contractToQuery), _tokenAddress ); } function oraclize_getPriceERC20( string memory _datasource, address _contractToQuery, uint256 _gasLimit ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _gasLimit, _contractToQuery), oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( byte _datasource, address _contractToQuery, uint256 _gasLimit ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _gasLimit, _contractToQuery), oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( string memory _datasource, address _contractToQuery, uint256 _gasLimit, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _gasLimit, _contractToQuery), _tokenAddress ); } function oraclize_getPriceERC20( byte _datasource, address _contractToQuery, uint256 _gasLimit, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { return oraclize.convertToERC20Price( oraclize.getPrice(_datasource, _gasLimit, _contractToQuery), _tokenAddress ); } function oraclize_getPriceERC20( byte _datasource, uint256 _gasLimit, uint256 _gasPrice ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, proofType_NONE ) ) ); return oraclize.convertToERC20Price( _queryPrice + _gasLimit * _gasPrice, oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( byte _datasource, uint256 _gasLimit, uint256 _gasPrice, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, proofType_NONE ) ) ); return oraclize.convertToERC20Price( _queryPrice + _gasLimit * _gasPrice, _tokenAddress ); } function oraclize_getPriceERC20( string memory _datasource, uint256 _gasLimit, uint256 _gasPrice, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, proofType_NONE ) ) ); return oraclize.convertToERC20Price( _queryPrice + _gasLimit * _gasPrice, _tokenAddress ); } function oraclize_getPriceERC20( byte _datasource, uint256 _gasLimit, uint256 _gasPrice, byte _proofType ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, _proofType ) ) ); return oraclize.convertToERC20Price( _queryPrice + _gasLimit * _gasPrice, oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( string memory _datasource, uint256 _gasLimit, uint256 _gasPrice ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, proofType_NONE ) ) ); return oraclize.convertToERC20Price( _queryPrice + _gasLimit * _gasPrice, oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( string memory _datasource, uint256 _gasLimit, uint256 _gasPrice, byte _proofType ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, _proofType ) ) ); return oraclize.convertToERC20Price( _queryPrice + _gasLimit * _gasPrice, oraclize.addressCustomPaymentToken(address(this)) ); } function oraclize_getPriceERC20( string memory _datasource, uint256 _gasLimit, uint256 _gasPrice, byte _proofType, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, _proofType ) ) ); return oraclize.convertToERC20Price( _queryPrice + _gasLimit * _gasPrice, _tokenAddress ); } function oraclize_getPriceERC20( bytes1 _datasource, uint256 _gasLimit, uint256 _gasPrice, byte _proofType, address _tokenAddress ) oraclizeAPI internal returns (uint256 _queryPrice) { _queryPrice = oraclize.price( keccak256( abi.encodePacked( _datasource, _proofType ) ) ); return oraclize.convertToERC20Price( _queryPrice + _gasLimit * _gasPrice, _tokenAddress ); } /** * * @notice `oraclize_query` overloads using STRING type datasource follow... * */ function oraclize_query( string memory _datasource, string memory _arg ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query(uint256,string,string)", 0, _datasource, _arg ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( bytes1 _datasource, string memory _arg ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query(uint256,bytes1,string)", 0, _datasource, _arg ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, string memory _datasource, string memory _arg ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query(uint256,string,string)", _timestamp, _datasource, _arg ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string memory _arg ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query(uint256,bytes1,string)", _timestamp, _datasource, _arg ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, string memory _datasource, string memory _arg, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query(uint256,string,string,uint256)", _timestamp, _datasource, _arg, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string memory _arg, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query(uint256,bytes1,string,uint256)", _timestamp, _datasource, _arg, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( string memory _datasource, string memory _arg, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query(uint256,string,string,uint256)", 0, _datasource, _arg, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( bytes1 _datasource, string memory _arg, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query(uint256,bytes1,string,uint256)", 0, _datasource, _arg, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( string memory _datasource, string memory _arg1, string memory _arg2 ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query2(uint256,string,string,string)", 0, _datasource, _arg1, _arg2 ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( bytes1 _datasource, string memory _arg1, string memory _arg2 ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query2(uint256,bytes1,string,string)", 0, _datasource, _arg1, _arg2 ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, string memory _datasource, string memory _arg1, string memory _arg2 ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query2(uint256,string,string,string)", _timestamp, _datasource, _arg1, _arg2 ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string memory _arg1, string memory _arg2 ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query2(uint256,bytes1,string,string)", _timestamp, _datasource, _arg1, _arg2 ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query2_withGasLimit(uint256,string,string,string,uint256)", _timestamp, _datasource, _arg1, _arg2, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string memory _arg1, string memory _arg2, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query2_withGasLimit(uint256,bytes1,string,string,uint256)", _timestamp, _datasource, _arg1, _arg2, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( string memory _datasource, string memory _arg1, string memory _arg2, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query2_withGasLimit(uint256,string,string,string,uint256)", 0, _datasource, _arg1, _arg2, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( bytes1 _datasource, string memory _arg1, string memory _arg2, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "query2_withGasLimit(uint256,bytes1,string,string,uint256)", 0, _datasource, _arg1, _arg2, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( string memory _datasource, string[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN(uint256,string,bytes)", 0, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( bytes1 _datasource, string[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN(uint256,bytes1,bytes)", 0, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, string memory _datasource, string[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN(uint256,string,bytes)", _timestamp, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN(uint256,bytes1,bytes)", _timestamp, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, string memory _datasource, string[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN_withGasLimit(uint256,string,bytes,uint256)", _timestamp, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN_withGasLimit(uint256,bytes1,bytes,uint256)", _timestamp, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( string memory _datasource, string[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN_withGasLimit(uint256,string,bytes,uint256)", 0, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( bytes1 _datasource, string[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN_withGasLimit(uint256,bytes1,bytes,uint256)", 0, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( string memory _datasource, bytes[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN(uint256,string,bytes)", 0, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( bytes1 _datasource, bytes[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN(uint256,bytes1,bytes)", 0, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN(uint256,string,bytes)", _timestamp, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN(uint256,bytes1,bytes)", _timestamp, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN_withGasLimit(uint256,string,bytes,uint256)", _timestamp, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN_withGasLimit(uint256,bytes1,bytes,uint256)", _timestamp, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( string memory _datasource, bytes[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN_withGasLimit(uint256,string,bytes,uint256)", 0, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_query( bytes1 _datasource, bytes[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call.value(price)(abi.encodeWithSignature( "queryN_withGasLimit(uint256,bytes1,bytes,uint256)", 0, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } /** * * @notice `oraclize_query` overloads using dynamic string[] arguments and * a datasource of type STRING follow... * */ function oraclize_query( string memory _datasource, string[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, string[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, string[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, string[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, string[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, string[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, string[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, string[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, string[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, string[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, string[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } /** * * @notice `oraclize_query` overloads using dynamic byte[] arguments and a * datasource of type STRING follow... * */ function oraclize_query( string memory _datasource, bytes[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, bytes[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, bytes[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, bytes[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, bytes[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, bytes[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, bytes[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, bytes[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, bytes[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, string memory _datasource, bytes[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( string memory _datasource, bytes[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } /** * * @notice `oraclize_query` overloads using dynamic string[] arguments and * a datasource of type BYTES1 follow... * */ function oraclize_query( bytes1 _datasource, string[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, string[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, string[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, string[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, string[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, string[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, string[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, string[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, string[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, string[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, string[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } /** * * @notice `oraclize_query` overloads using dynamic byte[] arguments and a * datasource of type BYTES1 follow... * */ function oraclize_query( bytes1 _datasource, bytes[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, bytes[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, bytes[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, bytes[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, bytes[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, bytes[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, bytes[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, bytes[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, bytes[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query( uint256 _timestamp, bytes1 _datasource, bytes[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query( bytes1 _datasource, bytes[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } /** * * @notice `oraclize_query` overloads end. * * @notice `oraclize_token_query` overloads using STRING datasource follow... * */ function oraclize_token_query( string memory _datasource, string memory _arg ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query(uint256,string,string)", 0, _datasource, _arg ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( bytes1 _datasource, string memory _arg ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query(uint256,bytes1,string)", 0, _datasource, _arg ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string memory _arg ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query(uint256,string,string)", _timestamp, _datasource, _arg ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string memory _arg ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query(uint256,bytes1,string)", _timestamp, _datasource, _arg ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string memory _arg, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query(uint256,string,string,uint256)", _timestamp, _datasource, _arg, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string memory _arg, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query(uint256,bytes1,string,uint256)", _timestamp, _datasource, _arg, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( string memory _datasource, string memory _arg, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query(uint256,string,string,uint256)", 0, _datasource, _arg, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( bytes1 _datasource, string memory _arg, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query(uint256,bytes1,string,uint256)", 0, _datasource, _arg, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( string memory _datasource, string memory _arg1, string memory _arg2 ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query2(uint256,string,string,string)", 0, _datasource, _arg1, _arg2 ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( bytes1 _datasource, string memory _arg1, string memory _arg2 ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query2(uint256,bytes1,string,string)", 0, _datasource, _arg1, _arg2 ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string memory _arg1, string memory _arg2 ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query2(uint256,string,string,string)", _timestamp, _datasource, _arg1, _arg2 ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string memory _arg1, string memory _arg2 ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query2(uint256,bytes1,string,string)", _timestamp, _datasource, _arg1, _arg2 ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query2_withGasLimit(uint256,string,string,string,uint256)", _timestamp, _datasource, _arg1, _arg2, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string memory _arg1, string memory _arg2, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query2_withGasLimit(uint256,bytes1,string,string,uint256)", _timestamp, _datasource, _arg1, _arg2, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( string memory _datasource, string memory _arg1, string memory _arg2, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query2_withGasLimit(uint256,string,string,string,uint256)", 0, _datasource, _arg1, _arg2, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( bytes1 _datasource, string memory _arg1, string memory _arg2, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "query2_withGasLimit(uint256,bytes1,string,string,uint256)", 0, _datasource, _arg1, _arg2, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( string memory _datasource, string[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN(uint256,string,bytes)", 0, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( bytes1 _datasource, string[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN(uint256,bytes1,bytes)", 0, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN(uint256,string,bytes)", _timestamp, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN(uint256,bytes1,bytes)", _timestamp, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN_withGasLimit(uint256,string,bytes,uint256)", _timestamp, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN_withGasLimit(uint256,bytes1,bytes,uint256)", _timestamp, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( string memory _datasource, string[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN_withGasLimit(uint256,string,bytes,uint256)", 0, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( bytes1 _datasource, string[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = stra2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN_withGasLimit(uint256,bytes1,bytes,uint256)", 0, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( string memory _datasource, bytes[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN(uint256,string,bytes)", 0, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( bytes1 _datasource, bytes[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN(uint256,bytes1,bytes)", 0, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN(uint256,string,bytes)", _timestamp, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[] memory _argN ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN(uint256,bytes1,bytes)", _timestamp, _datasource, args ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN_withGasLimit(uint256,string,bytes,uint256)", _timestamp, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN_withGasLimit(uint256,bytes1,bytes,uint256)", _timestamp, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( string memory _datasource, bytes[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN_withGasLimit(uint256,string,bytes,uint256)", 0, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } function oraclize_token_query( bytes1 _datasource, bytes[] memory _argN, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { uint256 price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Note: Return 0 due to unexpectedly high price } bytes memory args = ba2cbor(_argN); (bool success, bytes memory returnData) = address(oraclize) .call(abi.encodeWithSignature( "queryN_withGasLimit(uint256,bytes1,bytes,uint256)", 0, _datasource, args, _gasLimit ) ); require(success); bytes32 returnValue; assembly { returnValue := mload(add(returnData, 0x20)) } return returnValue; } /** * * @notice `oraclize_token_query` overloads using dynamic string[] * arguments and a datasource of type string follow... * */ function oraclize_token_query( string memory _datasource, string[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, string[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, string[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, string[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, string[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, string[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, string[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, string[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, string[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, string[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, string[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } /** * * @notice `oraclize_token_query` overloads using dynamic byte[] * arguments and a datasource of type string follow... * */ function oraclize_token_query( string memory _datasource, bytes[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, bytes[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, bytes[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, bytes[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, bytes[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, bytes[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, bytes[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, bytes[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, bytes[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, string memory _datasource, bytes[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( string memory _datasource, bytes[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } /** * * @notice `oraclize_token_query` overloads using dynamic string[] * arguments and a datasource of type bytes1 follow... * */ function oraclize_token_query( bytes1 _datasource, string[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, string[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, string[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, string[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, string[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, string[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, string[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, string[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, string[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, string[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, string[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } /** * * @notice `oraclize_token_query` overloads using dynamic byte[] arguments * and a datasource of type bytes1 follow... * */ function oraclize_token_query( bytes1 _datasource, bytes[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[1] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, bytes[1] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, bytes[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[2] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, bytes[2] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, bytes[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[3] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, bytes[3] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, bytes[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[4] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, bytes[4] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_token_query(_datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, bytes[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[5] memory _args ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_timestamp, _datasource, dynargs); } function oraclize_token_query( uint256 _timestamp, bytes1 _datasource, bytes[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_token_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_token_query( bytes1 _datasource, bytes[5] memory _args, uint256 _gasLimit ) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } /** * * @notice `oraclize_token_query` overloads end. * */ function oraclize_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); } function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) { return oraclize.cbAddress(); } function getCodeSize(address _addr) internal view returns (uint256 _size) { assembly { _size := extcodesize(_addr) } } function oraclize_setCustomGasPrice(uint256 _gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(_gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) { return oraclize.randomDS_getSessionPubKeyHash(); } function oraclize_requestQueryCaching(bytes32 _queryId) oraclizeAPI internal { return oraclize.requestQueryCaching(_queryId); } function oraclize_queryCached(uint256 _queryPrice) oraclizeAPI internal returns (bytes32 _queryId) { return oraclize.queryCached.value(_queryPrice)(); } function oraclize_getDatasourceByte( string memory _datasourceString ) internal pure returns (byte _datasourceByte) { if (keccak256(abi.encodePacked(_datasourceString)) == keccak256('URL')) return 0xFF; if (keccak256(abi.encodePacked(_datasourceString)) == keccak256('Random')) return 0xFE; if (keccak256(abi.encodePacked(_datasourceString)) == keccak256('computation')) return 0xFD; if (keccak256(abi.encodePacked(_datasourceString)) == keccak256('WolframAlpha')) return 0xFC; if (keccak256(abi.encodePacked(_datasourceString)) == keccak256('IPFS')) return 0xFB; if (keccak256(abi.encodePacked(_datasourceString)) == keccak256('nested')) return 0xFA; if (keccak256(abi.encodePacked(_datasourceString)) == keccak256('Blockchain')) return 0xF9; if (keccak256(abi.encodePacked(_datasourceString)) == keccak256('swarm')) return 0xF8; return 0x00; } function oraclize_getRebroadcastCost( uint256 _gasLimit, uint256 _gasPrice ) oraclizeAPI internal returns(uint256 _rebroadcastCost) { return oraclize.getRebroadcastCost(_gasLimit, _gasPrice); } function oraclize_requestCallbackRebroadcast( bytes32 _queryId, uint256 _gasLimit, uint256 _gasPrice, uint256 _queryPrice ) oraclizeAPI internal { return oraclize .requestCallbackRebroadcast .value(_queryPrice) ( _queryId, _gasLimit, _gasPrice ); } function oraclize_setCustomTokenPayment(address _tokenAddress) oraclizeAPI internal { return oraclize.setCustomTokenPayment(_tokenAddress); } function oraclize_approveTokenAllowance( address _tokenAddress, uint256 _tokenAmount ) oraclizeAPI internal { ERC20Interface(_tokenAddress) .approve(address(oraclize), _tokenAmount); } function oraclize_setAndApproveCustomTokenPayment( address _tokenAddress, uint256 _tokenAmount ) oraclizeAPI internal { oraclize_setCustomTokenPayment(_tokenAddress); oraclize_approveTokenAllowance(_tokenAddress, _tokenAmount); } function oraclize_unsetAndRevokeCustomTokenPayment(address _tokenAddress) oraclizeAPI internal { oraclize_unsetCustomTokenPayment(); oraclize_approveTokenAllowance(_tokenAddress, 0); } function oraclize_unsetCustomTokenPayment() oraclizeAPI internal { return oraclize.unsetCustomTokenPayment(); } /** * * @notice Oraclize helper functions follow... * */ function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint256 i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare( string memory _a, string memory _b ) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint256 minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint256 i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf( string memory _haystack, string memory _needle ) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint256 subindex = 0; for (uint256 i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while( subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex] ) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat( string memory _a, string memory _b ) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat( string memory _a, string memory _b, string memory _c ) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d ) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d, string memory _e ) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string( _ba.length + _bb.length + _bc.length + _bd.length + _be.length ); bytes memory babcde = bytes(abcde); uint256 k = 0; uint256 i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint256 _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt( string memory _a, uint256 _b ) internal pure returns (uint256 _parsedInt) { bytes memory bresult = bytes(_a); uint256 mint = 0; bool decimals = false; for (uint256 i = 0; i < bresult.length; i++) { if ( (uint256(uint8(bresult[i])) >= 48) && (uint256(uint8(bresult[i])) <= 57) ) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint256(uint8(bresult[i])) - 48; } else if (uint256(uint8(bresult[i])) == 46) { require( !decimals, 'More than one decimal encountered in string!' ); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint256 _parsedInt) { return parseInt(_a, 0); } function parseInt( string memory _a, uint256 _b ) internal pure returns (uint256 _parsedInt) { bytes memory bresult = bytes(_a); uint256 mint = 0; bool decimals = false; for (uint256 i = 0; i < bresult.length; i++) { if ( (uint256(uint8(bresult[i])) >= 48) && (uint256(uint8(bresult[i])) <= 57) ) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint256(uint8(bresult[i])) - 48; } else if (uint256(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint256 i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint256 i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } /** * * Oraclize RandomDS Functions * */ function oraclize_newRandomDSQuery( uint256 _delay, uint256 _nbytes, uint256 _customGasLimit ) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Note: Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /** * * The following variables can be relaxed. * Check the relaxed random contract at https://github.com/oraclize/ethereum-examples * for an idea on how to override and replace commit hash variables. * */ mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8( add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000) ) mstore8( add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000) ) mstore8( add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000) ) mstore8( add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000) ) mstore8( add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000) ) mstore8( add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000) ) mstore8( add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000) ) mstore8( add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000) ) } oraclize_randomDS_setCommitment( queryId, keccak256( abi.encodePacked( delay_bytes8_left, args[1], sha256(args[0]), args[2] ) ) ); return queryId; } function oraclize_randomDS_setCommitment( bytes32 _queryId, bytes32 _commitment ) internal { oraclize_randomDS_args[_queryId] = _commitment; } function verifySig( bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey ) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint256 offset = 4 + (uint256(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes( _dersig, offset + (uint256(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0 ); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity( bytes memory _proof, uint256 _sig2offset ) internal returns (bool _proofVerified) { bool sigok; /** * * Note - Random DS Proof Step 6: * Verify the attestation signature, APPKEY1 must sign the sessionKey * from the correct ledger app (CODEHASH) * */ bytes memory sig2 = new bytes(uint256(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } /** * * Note - Random DS Proof Step 7: * Verify the APPKEY1 provenance (must be signed by Ledger) * */ bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint256(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode( bytes32 _queryId, string memory _result, bytes memory _proof ) internal returns (uint8 _returnCode) { /** * * Note - Random DS Proof Step 1: * The prefix has to match 'LP\x01' (Ledger Proof version 1) * */ if ( (_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1)) ) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main( _proof, _queryId, bytes(_result), oraclize_getNetworkName() ); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix( bytes32 _content, bytes memory _prefix, uint256 _nRandomBytes ) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function oraclize_randomDS_proofVerify__main( bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName ) internal returns (bool _proofVerified) { /** * * Note - Random DS Proof Step 2: * The unique keyhash has to match with the sha256 of: * (context name + _queryId) * */ uint256 ledgerProofLength = 3 + 65 + (uint256(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint256(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); /** * * Note - Random DS Proof Step 3: * We assume sig1 is valid (it will be verified during step 5) and we * verify if '_result' is the _prefix of sha256(sig1) * */ if (!matchBytes32Prefix(sha256(sig1), _result, uint256(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } /** * * Note - Random DS Proof Step 4: * Commitment match verifying that * * keccak256( * delay, * nbytes, * unonce, * sessionKeyHash * ) == commitment in storage. * * This is to verify that the computed args match with the ones * specified in the query. * */ bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint256 sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[_queryId]; } else { return false; } /** * * Note - Random DS Proof Step 5: * Validity verification for sig1 (keyhash and args signed with the * sessionKey) * */ bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } /** * * Note: Verify if sessionPubkeyHash was verified already, if not... * let's do it! * */ if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /** * * The following function has been written by Alex Beregszaszi * Use it under the terms of the MIT license * */ function copyBytes( bytes memory _from, uint256 _fromOffset, uint256 _length, bytes memory _to, uint256 _toOffset ) internal pure returns (bytes memory _copiedBytes) { uint256 minLength = _length + _toOffset; require(_to.length >= minLength); // Note: Buffer too small. Should be a better way? uint256 i = 32 + _fromOffset; // Note: the offset 32 is added to skip the `size` field of both bytes variables uint256 j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /** * * The following function has been written by Alex Beregszaszi * Use it under the terms of the MIT license * It duplicates Solidity's ecrecover, but catching the CALL return value * */ function safer_ecrecover( bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s ) internal returns (bool _success, address _recoveredAddress) { /** * * We do our own memory management here. Solidity uses memory offset * 0x40 to store the current end of memory. We write past it (as * writes are memory extensions), but don't update the offset so * Solidity will reuse it. The memory used here is only needed for * this context. * FIXME: inline assembly can't access return values * */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /** * * The following function has been written by Alex Beregszaszi, use it under the terms of the MIT license * */ function ecrecovery( bytes32 _hash, bytes memory _sig ) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /** * * The signature format is a compact form of: * {bytes32 r}{bytes32 s}{uint8 v} * Compact means, uint8 is not padded to 32 bytes. * */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /** * * Here we are loading the last 32 bytes. We exploit the fact that * 'mload' will pad with zeroes if we overread. * There is no 'mload8' to do this, but that would be nicer. * */ v := byte(0, mload(add(_sig, 96))) /** * * Alternative solution: * 'byte' is not working due to the Solidity parser, so lets * use the second best option, 'and' * v := and(mload(add(_sig, 65)), 255) * */ } /** * * albeit non-transactional signatures are not specified by the YP, one * would expect it to match the YP range of [27, 28] * geth uses [0, 1] and some clients have followed. This might change, * see: https://github.com/ethereum/go-ethereum/issues/2053 * */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } /** * * END ORACLIZE_API * */
`oraclize_token_query` overloads end./
function oraclize_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); }
6,456,454
pragma solidity ^0.5.11; // Public-Sale for #3277-12000 stage of Voken2.0 // // More info: // https://vision.network // https://voken.io // // Contact us: // [email protected] // [email protected] /** * @dev Uint256 wrappers over Solidity's arithmetic operations with added overflow checks. */ library SafeMath256 { /** * @dev Returns the addition of two unsigned integers, reverting on 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). */ 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). */ 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. */ 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. Reverts on * division by zero. The result is rounded towards 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. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Uint16 wrappers over Solidity's arithmetic operations with added overflow checks. */ library SafeMath16 { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. */ function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 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). */ function sub(uint16 a, uint16 b) internal pure returns (uint16) { 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). */ function sub(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b <= a, errorMessage); uint16 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. */ function mul(uint16 a, uint16 b) internal pure returns (uint16) { if (a == 0) { return 0; } uint16 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. */ function div(uint16 a, uint16 b) internal pure returns (uint16) { 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. */ function div(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. */ function mod(uint16 a, uint16 b) internal pure returns (uint16) { 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. */ function mod(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b != 0, errorMessage); return a % b; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @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. */ contract Ownable { address internal _owner; address internal _newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event OwnershipAccepted(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the addresses of the current and new owner. */ function owner() public view returns (address currentOwner, address newOwner) { currentOwner = _owner; newOwner = _newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(msg.sender), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner(address account) public view returns (bool) { return account == _owner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * IMPORTANT: Need to run {acceptOwnership} by the new owner. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _newOwner = newOwner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Accept ownership of the contract. * * Can only be called by the new owner. */ function acceptOwnership() public { require(msg.sender == _newOwner, "Ownable: caller is not the new owner address"); require(msg.sender != address(0), "Ownable: caller is the zero address"); emit OwnershipAccepted(_owner, msg.sender); _owner = msg.sender; _newOwner = address(0); } /** * @dev Rescue compatible ERC20 Token * * Can only be called by the current owner. */ function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner { IERC20 _token = IERC20(tokenAddr); require(recipient != address(0), "Rescue: recipient is the zero address"); uint256 balance = _token.balanceOf(address(this)); require(balance >= amount, "Rescue: amount exceeds balance"); _token.transfer(recipient, amount); } /** * @dev Withdraw Ether * * Can only be called by the current owner. */ function withdrawEther(address payable recipient, uint256 amount) external onlyOwner { require(recipient != address(0), "Withdraw: recipient is the zero address"); uint256 balance = address(this).balance; require(balance >= amount, "Withdraw: amount exceeds balance"); recipient.transfer(amount); } } /** * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { bool private _paused; event Paused(address account); event Unpaused(address account); /** * @dev Constructor */ constructor () internal { _paused = false; } /** * @return Returns true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Paused"); _; } /** * @dev Sets paused state. * * Can only be called by the current owner. */ function setPaused(bool value) external onlyOwner { _paused = value; if (_paused) { emit Paused(msg.sender); } else { emit Unpaused(msg.sender); } } } /** * @dev Part of ERC20 interface. */ interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } /** * @title Voken2.0 interface. */ interface IVoken2 { function balanceOf(address owner) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function mint(address account, uint256 amount) external returns (bool); function mintWithAllocation(address account, uint256 amount, address allocationContract) external returns (bool); function whitelisted(address account) external view returns (bool); function whitelistReferee(address account) external view returns (address payable); function whitelistReferralsCount(address account) external view returns (uint256); } /** * @dev Interface of an allocation contract */ interface IAllocation { function reservedOf(address account) external view returns (uint256); } /** * @dev Allocation for VOKEN */ library Allocations { struct Allocation { uint256 amount; uint256 timestamp; } } /** * @title VokenShareholders interface. */ interface VokenShareholders { // } /** * @title Voken Public Sale v2.0 */ contract VokenPublicSale2 is Ownable, Pausable, IAllocation { using SafeMath16 for uint16; using SafeMath256 for uint256; using Roles for Roles.Role; using Allocations for Allocations.Allocation; // Proxy Roles.Role private _proxies; // Addresses IVoken2 private _VOKEN = IVoken2(0xFfFAb974088Bd5bF3d7E6F522e93Dd7861264cDB); VokenShareholders private _SHAREHOLDERS = VokenShareholders(0x7712F76D2A52141D44461CDbC8b660506DCAB752); address payable private _TEAM; // Referral rewards, 35% for 15 levels uint16[15] private REWARDS_PCT = [6, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]; // Limit uint16[] private LIMIT_COUNTER = [1, 3, 10, 50, 100, 200, 300]; uint256[] private LIMIT_WEIS = [100 ether, 50 ether, 40 ether, 30 ether, 20 ether, 10 ether, 5 ether]; uint256 private LIMIT_WEI_MIN = 3 ether; // 6,000 000 gas mininum uint24 private GAS_MIN = 6000000; // Price uint256 private VOKEN_USD_PRICE_START = 1000; // $ 0.00100 USD uint256 private VOKEN_USD_PRICE_STEP = 10; // $ + 0.00001 USD uint256 private STAGE_USD_CAP_START = 100000000; // $ 100 USD uint256 private STAGE_USD_CAP_STEP = 1000000; // $ +1 USD uint256 private STAGE_USD_CAP_MAX = 15100000000; // $ 15,100 USD // 1 Ether|Voken = xx.xxxxxx USD, with 6 decimals uint256 private _etherUsdPrice; uint256 private _vokenUsdPrice; // Progress uint16 private SEASON_MAX = 100; // 100 seasons max uint16 private SEASON_LIMIT = 20; // 20 season total uint16 private SEASON_STAGES = 600; // each 600 stages is a season uint16 private STAGE_MAX = SEASON_STAGES.mul(SEASON_MAX); uint16 private STAGE_LIMIT = SEASON_STAGES.mul(SEASON_LIMIT); uint16 private _stage; uint16 private _season; // Sum uint256 private _txs; uint256 private _vokenIssued; uint256 private _vokenIssuedTxs; uint256 private _vokenBonus; uint256 private _vokenBonusTxs; uint256 private _weiSold; uint256 private _weiRewarded; uint256 private _weiShareholders; uint256 private _weiTeam; uint256 private _weiPended; uint256 private _usdSold; uint256 private _usdRewarded; // Shareholders ratio uint256 private SHAREHOLDERS_RATIO_START = 15000000; // 15%, with 8 decimals uint256 private SHAREHOLDERS_RATIO_DISTANCE = 50000000; // 50%, with 8 decimals uint256 private _shareholdersRatio; // Cache bool private _cacheWhitelisted; uint256 private _cacheWeiShareholders; uint256 private _cachePended; uint16[] private _cacheRewards; address payable[] private _cacheReferees; // Allocations mapping (address => Allocations.Allocation[]) private _allocations; // Account mapping (address => uint256) private _accountVokenIssued; mapping (address => uint256) private _accountVokenBonus; mapping (address => uint256) private _accountVokenReferral; mapping (address => uint256) private _accountVokenReferrals; mapping (address => uint256) private _accountUsdPurchased; mapping (address => uint256) private _accountWeiPurchased; mapping (address => uint256) private _accountUsdRewarded; mapping (address => uint256) private _accountWeiRewarded; // Stage mapping (uint16 => uint256) private _stageUsdSold; mapping (uint16 => uint256) private _stageVokenIssued; mapping (uint16 => uint256) private _stageVokenBonus; // Season mapping (uint16 => uint256) private _seasonWeiSold; mapping (uint16 => uint256) private _seasonWeiRewarded; mapping (uint16 => uint256) private _seasonWeiShareholders; mapping (uint16 => uint256) private _seasonWeiPended; mapping (uint16 => uint256) private _seasonUsdSold; mapping (uint16 => uint256) private _seasonUsdRewarded; mapping (uint16 => uint256) private _seasonUsdShareholders; mapping (uint16 => uint256) private _seasonVokenIssued; mapping (uint16 => uint256) private _seasonVokenBonus; // Account in season mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountIssued; mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountBonus; mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferral; mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferrals; mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountPurchased; mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountReferrals; mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountRewarded; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountPurchased; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountReferrals; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountRewarded; // Season wei limit accounts mapping (uint16 => mapping (uint256 => address[])) private _seasonLimitAccounts; mapping (uint16 => address[]) private _seasonLimitWeiMinAccounts; // Referrals mapping (uint16 => address[]) private _seasonAccounts; mapping (uint16 => address[]) private _seasonReferrals; mapping (uint16 => mapping (address => bool)) private _seasonHasAccount; mapping (uint16 => mapping (address => bool)) private _seasonHasReferral; mapping (uint16 => mapping (address => address[])) private _seasonAccountReferrals; mapping (uint16 => mapping (address => mapping (address => bool))) private _seasonAccountHasReferral; // Events event ProxyAdded(address indexed account); event ProxyRemoved(address indexed account); event StageClosed(uint256 _stageNumber); event SeasonClosed(uint16 _seasonNumber); event AuditEtherPriceUpdated(uint256 value, address indexed account); event Log(uint256 value); /** * @dev Throws if called by account which is not a proxy. */ modifier onlyProxy() { require(isProxy(msg.sender), "ProxyRole: caller does not have the Proxy role"); _; } /** * @dev Returns true if the `account` has the Proxy role. */ function isProxy(address account) public view returns (bool) { return _proxies.has(account); } /** * @dev Give an `account` access to the Proxy role. * * Can only be called by the current owner. */ function addProxy(address account) public onlyOwner { _proxies.add(account); emit ProxyAdded(account); } /** * @dev Remove an `account` access from the Proxy role. * * Can only be called by the current owner. */ function removeProxy(address account) public onlyOwner { _proxies.remove(account); emit ProxyRemoved(account); } /** * @dev Returns the VOKEN address. */ function VOKEN() public view returns (IVoken2) { return _VOKEN; } /** * @dev Returns the shareholders contract address. */ function SHAREHOLDERS() public view returns (VokenShareholders) { return _SHAREHOLDERS; } /** * @dev Returns the team wallet address. */ function TEAM() public view returns (address) { return _TEAM; } /** * @dev Returns the main status. */ function status() public view returns (uint16 stage, uint16 season, uint256 etherUsdPrice, uint256 vokenUsdPrice, uint256 shareholdersRatio) { if (_stage > STAGE_MAX) { stage = STAGE_MAX; season = SEASON_MAX; } else { stage = _stage; season = _season; } etherUsdPrice = _etherUsdPrice; vokenUsdPrice = _vokenUsdPrice; shareholdersRatio = _shareholdersRatio; } /** * @dev Returns the sum. */ function sum() public view returns(uint256 vokenIssued, uint256 vokenBonus, uint256 weiSold, uint256 weiRewarded, uint256 weiShareholders, uint256 weiTeam, uint256 weiPended, uint256 usdSold, uint256 usdRewarded) { vokenIssued = _vokenIssued; vokenBonus = _vokenBonus; weiSold = _weiSold; weiRewarded = _weiRewarded; weiShareholders = _weiShareholders; weiTeam = _weiTeam; weiPended = _weiPended; usdSold = _usdSold; usdRewarded = _usdRewarded; } /** * @dev Returns the transactions' counter. */ function transactions() public view returns(uint256 txs, uint256 vokenIssuedTxs, uint256 vokenBonusTxs) { txs = _txs; vokenIssuedTxs = _vokenIssuedTxs; vokenBonusTxs = _vokenBonusTxs; } /** * @dev Returns the `account` data. */ function queryAccount(address account) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 vokenReferral, uint256 vokenReferrals, uint256 weiPurchased, uint256 weiRewarded, uint256 usdPurchased, uint256 usdRewarded) { vokenIssued = _accountVokenIssued[account]; vokenBonus = _accountVokenBonus[account]; vokenReferral = _accountVokenReferral[account]; vokenReferrals = _accountVokenReferrals[account]; weiPurchased = _accountWeiPurchased[account]; weiRewarded = _accountWeiRewarded[account]; usdPurchased = _accountUsdPurchased[account]; usdRewarded = _accountUsdRewarded[account]; } /** * @dev Returns the stage data by `stageIndex`. */ function stage(uint16 stageIndex) public view returns (uint256 vokenUsdPrice, uint256 shareholdersRatio, uint256 vokenIssued, uint256 vokenBonus, uint256 vokenCap, uint256 vokenOnSale, uint256 usdSold, uint256 usdCap, uint256 usdOnSale) { if (stageIndex <= STAGE_LIMIT) { vokenUsdPrice = _calcVokenUsdPrice(stageIndex); shareholdersRatio = _calcShareholdersRatio(stageIndex); vokenIssued = _stageVokenIssued[stageIndex]; vokenBonus = _stageVokenBonus[stageIndex]; vokenCap = _stageVokenCap(stageIndex); vokenOnSale = vokenCap.sub(vokenIssued); usdSold = _stageUsdSold[stageIndex]; usdCap = _stageUsdCap(stageIndex); usdOnSale = usdCap.sub(usdSold); } } /** * @dev Returns the season data by `seasonNumber`. */ function season(uint16 seasonNumber) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 weiSold, uint256 weiRewarded, uint256 weiShareholders, uint256 weiPended, uint256 usdSold, uint256 usdRewarded, uint256 usdShareholders) { if (seasonNumber <= SEASON_LIMIT) { vokenIssued = _seasonVokenIssued[seasonNumber]; vokenBonus = _seasonVokenBonus[seasonNumber]; weiSold = _seasonWeiSold[seasonNumber]; weiRewarded = _seasonWeiRewarded[seasonNumber]; weiShareholders = _seasonWeiShareholders[seasonNumber]; weiPended = _seasonWeiPended[seasonNumber]; usdSold = _seasonUsdSold[seasonNumber]; usdRewarded = _seasonUsdRewarded[seasonNumber]; usdShareholders = _seasonUsdShareholders[seasonNumber]; } } /** * @dev Returns the `account` data of #`seasonNumber` season. */ function accountInSeason(address account, uint16 seasonNumber) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 vokenReferral, uint256 vokenReferrals, uint256 weiPurchased, uint256 weiReferrals, uint256 weiRewarded, uint256 usdPurchased, uint256 usdReferrals, uint256 usdRewarded) { if (seasonNumber > 0 && seasonNumber <= SEASON_LIMIT) { vokenIssued = _vokenSeasonAccountIssued[seasonNumber][account]; vokenBonus = _vokenSeasonAccountBonus[seasonNumber][account]; vokenReferral = _vokenSeasonAccountReferral[seasonNumber][account]; vokenReferrals = _vokenSeasonAccountReferrals[seasonNumber][account]; weiPurchased = _weiSeasonAccountPurchased[seasonNumber][account]; weiReferrals = _weiSeasonAccountReferrals[seasonNumber][account]; weiRewarded = _weiSeasonAccountRewarded[seasonNumber][account]; usdPurchased = _usdSeasonAccountPurchased[seasonNumber][account]; usdReferrals = _usdSeasonAccountReferrals[seasonNumber][account]; usdRewarded = _usdSeasonAccountRewarded[seasonNumber][account]; } } /** * @dev Referral accounts in a season by `seasonNumber`. */ function seasonReferrals(uint16 seasonNumber) public view returns (address[] memory) { return _seasonReferrals[seasonNumber]; } /** * @dev Referral accounts in a season by `seasonNumber` of `account`. */ function seasonAccountReferrals(uint16 seasonNumber, address account) public view returns (address[] memory) { return _seasonAccountReferrals[seasonNumber][account]; } /** * @dev Voken price in USD, by `stageIndex`. */ function _calcVokenUsdPrice(uint16 stageIndex) private view returns (uint256) { return VOKEN_USD_PRICE_START.add(VOKEN_USD_PRICE_STEP.mul(stageIndex)); } /** * @dev Returns the shareholders ratio by `stageIndex`. */ function _calcShareholdersRatio(uint16 stageIndex) private view returns (uint256) { return SHAREHOLDERS_RATIO_START.add(SHAREHOLDERS_RATIO_DISTANCE.mul(stageIndex).div(STAGE_MAX)); } /** * @dev Returns the dollor cap of `stageIndex`. */ function _stageUsdCap(uint16 stageIndex) private view returns (uint256) { uint256 __usdCap = STAGE_USD_CAP_START.add(STAGE_USD_CAP_STEP.mul(stageIndex)); if (__usdCap > STAGE_USD_CAP_MAX) { return STAGE_USD_CAP_MAX; } return __usdCap; } /** * @dev Returns the Voken cap of `stageIndex`. */ function _stageVokenCap(uint16 stageIndex) private view returns (uint256) { return _stageUsdCap(stageIndex).mul(1000000).div(_calcVokenUsdPrice(stageIndex)); } /** * @dev Returns an {uint256} by `value` * _shareholdersRatio / 100000000 */ function _2shareholders(uint256 value) private view returns (uint256) { return value.mul(_shareholdersRatio).div(100000000); } /** * @dev wei => USD, by `weiAmount`. */ function _wei2usd(uint256 weiAmount) private view returns (uint256) { return weiAmount.mul(_etherUsdPrice).div(1 ether); } /** * @dev USD => wei, by `usdAmount`. */ function _usd2wei(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1 ether).div(_etherUsdPrice); } /** * @dev USD => voken, by `usdAmount`. */ function _usd2voken(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1000000).div(_vokenUsdPrice); } /** * @dev Returns the season number by `stageIndex`. */ function _seasonNumber(uint16 stageIndex) private view returns (uint16) { if (stageIndex > 0) { uint16 __seasonNumber = stageIndex.div(SEASON_STAGES); if (stageIndex.mod(SEASON_STAGES) > 0) { return __seasonNumber.add(1); } return __seasonNumber; } return 1; } /** * Close the current stage. */ function _closeStage() private { _stage = _stage.add(1); emit StageClosed(_stage); // Close current season uint16 __seasonNumber = _seasonNumber(_stage); if (_season < __seasonNumber) { _season = __seasonNumber; emit SeasonClosed(_season); } _vokenUsdPrice = _calcVokenUsdPrice(_stage); _shareholdersRatio = _calcShareholdersRatio(_stage); } /** * @dev Update audit ether price. */ function updateEtherUsdPrice(uint256 value) external onlyProxy { _etherUsdPrice = value; emit AuditEtherPriceUpdated(value, msg.sender); } /** * @dev Update team wallet address. */ function updateTeamWallet(address payable account) external onlyOwner { _TEAM = account; } /** * @dev Returns current max wei value. */ function weiMax() public view returns (uint256) { for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (_seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) { return LIMIT_WEIS[i]; } } return LIMIT_WEI_MIN; } /** * @dev Returns the {limitIndex} and {weiMax}. */ function _limit(uint256 weiAmount) private view returns (uint256 __wei) { uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender]; for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (__purchased >= LIMIT_WEIS[i]) { return 0; } if (__purchased < LIMIT_WEIS[i]) { __wei = LIMIT_WEIS[i].sub(__purchased); if (weiAmount >= __wei && _seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) { return __wei; } } } if (__purchased < LIMIT_WEI_MIN) { return LIMIT_WEI_MIN.sub(__purchased); } } /** * @dev Updates the season limit accounts, or wei min accounts. */ function _updateSeasonLimits() private { uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender]; if (__purchased > LIMIT_WEI_MIN) { for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (__purchased >= LIMIT_WEIS[i]) { _seasonLimitAccounts[_season][i].push(msg.sender); return; } } } else if (__purchased == LIMIT_WEI_MIN) { _seasonLimitWeiMinAccounts[_season].push(msg.sender); return; } } /** * @dev Returns the accounts of wei limit, by `seasonNumber` and `limitIndex`. */ function seasonLimitAccounts(uint16 seasonNumber, uint16 limitIndex) public view returns (uint256 weis, address[] memory accounts) { if (limitIndex < LIMIT_WEIS.length) { weis = LIMIT_WEIS[limitIndex]; accounts = _seasonLimitAccounts[seasonNumber][limitIndex]; } else { weis = LIMIT_WEI_MIN; accounts = _seasonLimitWeiMinAccounts[seasonNumber]; } } /** * @dev constructor */ constructor () public { _stage = 3277; _season = _seasonNumber(_stage); _vokenUsdPrice = _calcVokenUsdPrice(_stage); _shareholdersRatio = _calcShareholdersRatio(_stage); _TEAM = msg.sender; addProxy(msg.sender); } /** * @dev Receive ETH, and excute the exchange. */ function () external payable whenNotPaused { require(_etherUsdPrice > 0, "VokenPublicSale2: Audit ETH price is zero"); require(_stage <= STAGE_MAX, "VokenPublicSale2: Voken Public-Sale Completled"); uint256 __usdAmount; uint256 __usdRemain; uint256 __usdUsed; uint256 __weiUsed; uint256 __voken; // Limit uint256 __weiMax = _limit(msg.value); if (__weiMax < msg.value) { __usdAmount = _wei2usd(__weiMax); } else { __usdAmount = _wei2usd(msg.value); } __usdRemain = __usdAmount; if (__usdRemain > 0) { // cache _cache(); // USD => Voken while (gasleft() > GAS_MIN && __usdRemain > 0 && _stage <= STAGE_LIMIT) { uint256 __txVokenIssued; (__txVokenIssued, __usdRemain) = _tx(__usdRemain); __voken = __voken.add(__txVokenIssued); } // Used __usdUsed = __usdAmount.sub(__usdRemain); __weiUsed = _usd2wei(__usdUsed); // Whitelist if (_cacheWhitelisted && __voken > 0) { _mintVokenBonus(__voken); for(uint16 i = 0; i < _cacheReferees.length; i++) { address payable __referee = _cacheReferees[i]; uint256 __usdReward = __usdUsed.mul(_cacheRewards[i]).div(100); uint256 __weiReward = __weiUsed.mul(_cacheRewards[i]).div(100); __referee.transfer(__weiReward); _usdRewarded = _usdRewarded.add(__usdReward); _weiRewarded = _weiRewarded.add(__weiReward); _accountUsdRewarded[__referee] = _accountUsdRewarded[__referee].add(__usdReward); _accountWeiRewarded[__referee] = _accountWeiRewarded[__referee].add(__weiReward); } if (_cachePended > 0) { _weiPended = _weiPended.add(__weiUsed.mul(_cachePended).div(100)); } } // Counter if (__weiUsed > 0) { _txs = _txs.add(1); _usdSold = _usdSold.add(__usdUsed); _weiSold = _weiSold.add(__weiUsed); _accountUsdPurchased[msg.sender] = _accountUsdPurchased[msg.sender].add(__usdUsed); _accountWeiPurchased[msg.sender] = _accountWeiPurchased[msg.sender].add(__weiUsed); // Wei for SHAREHOLDERS _weiShareholders = _weiShareholders.add(_cacheWeiShareholders); (bool __bool,) = address(_SHAREHOLDERS).call.value(_cacheWeiShareholders)(""); assert(__bool); // Wei for TEAM uint256 __weiTeam = _weiSold.sub(_weiRewarded).sub(_weiShareholders).sub(_weiPended).sub(_weiTeam); _weiTeam = _weiTeam.add(__weiTeam); _TEAM.transfer(__weiTeam); // Update season limits _updateSeasonLimits(); } // Reset cache _resetCache(); } // If wei remains, refund. uint256 __weiRemain = msg.value.sub(__weiUsed); if (__weiRemain > 0) { msg.sender.transfer(__weiRemain); } } /** * @dev Cache. */ function _cache() private { if (!_seasonHasAccount[_season][msg.sender]) { _seasonAccounts[_season].push(msg.sender); _seasonHasAccount[_season][msg.sender] = true; } _cacheWhitelisted = _VOKEN.whitelisted(msg.sender); if (_cacheWhitelisted) { address __account = msg.sender; for(uint16 i = 0; i < REWARDS_PCT.length; i++) { address __referee = _VOKEN.whitelistReferee(__account); if (__referee != address(0) && __referee != __account && _VOKEN.whitelistReferralsCount(__referee) > i) { if (!_seasonHasReferral[_season][__referee]) { _seasonReferrals[_season].push(__referee); _seasonHasReferral[_season][__referee] = true; } if (!_seasonAccountHasReferral[_season][__referee][__account]) { _seasonAccountReferrals[_season][__referee].push(__account); _seasonAccountHasReferral[_season][__referee][__account] = true; } _cacheReferees.push(address(uint160(__referee))); _cacheRewards.push(REWARDS_PCT[i]); } else { _cachePended = _cachePended.add(REWARDS_PCT[i]); } __account = __referee; } } } /** * @dev Reset cache. */ function _resetCache() private { delete _cacheWeiShareholders; if (_cacheWhitelisted) { delete _cacheWhitelisted; delete _cacheReferees; delete _cacheRewards; delete _cachePended; } } /** * @dev USD => Voken */ function _tx(uint256 __usd) private returns (uint256 __voken, uint256 __usdRemain) { uint256 __stageUsdCap = _stageUsdCap(_stage); uint256 __usdUsed; // in stage if (_stageUsdSold[_stage].add(__usd) <= __stageUsdCap) { __usdUsed = __usd; (__voken, ) = _calcExchange(__usdUsed); _mintVokenIssued(__voken); // close stage, if stage dollor cap reached if (__stageUsdCap == _stageUsdSold[_stage]) { _closeStage(); } } // close stage else { __usdUsed = __stageUsdCap.sub(_stageUsdSold[_stage]); (__voken, ) = _calcExchange(__usdUsed); _mintVokenIssued(__voken); _closeStage(); __usdRemain = __usd.sub(__usdUsed); } } /** * @dev USD => voken & wei, and make records. */ function _calcExchange(uint256 __usd) private returns (uint256 __voken, uint256 __wei) { __wei = _usd2wei(__usd); __voken = _usd2voken(__usd); uint256 __usdShareholders = _2shareholders(__usd); uint256 __weiShareholders = _usd2wei(__usdShareholders); // Stage: usd _stageUsdSold[_stage] = _stageUsdSold[_stage].add(__usd); // Season: usd, wei _seasonUsdSold[_season] = _seasonUsdSold[_season].add(__usd); _seasonWeiSold[_season] = _seasonWeiSold[_season].add(__wei); // Season: wei pended if (_cachePended > 0) { _seasonWeiPended[_season] = _seasonWeiPended[_season].add(__wei.mul(_cachePended).div(100)); } // Season shareholders: usd, wei _seasonUsdShareholders[_season] = _seasonUsdShareholders[_season].add(__usdShareholders); _seasonWeiShareholders[_season] = _seasonWeiShareholders[_season].add(__weiShareholders); // Cache _cacheWeiShareholders = _cacheWeiShareholders.add(__weiShareholders); // Season => account: usd, wei _usdSeasonAccountPurchased[_season][msg.sender] = _usdSeasonAccountPurchased[_season][msg.sender].add(__usd); _weiSeasonAccountPurchased[_season][msg.sender] = _weiSeasonAccountPurchased[_season][msg.sender].add(__wei); // season referral account if (_cacheWhitelisted) { for (uint16 i = 0; i < _cacheRewards.length; i++) { address __referee = _cacheReferees[i]; uint256 __usdReward = __usd.mul(_cacheRewards[i]).div(100); uint256 __weiReward = __wei.mul(_cacheRewards[i]).div(100); // season _seasonUsdRewarded[_season] = _seasonUsdRewarded[_season].add(__usdReward); _seasonWeiRewarded[_season] = _seasonWeiRewarded[_season].add(__weiReward); // season => account _usdSeasonAccountRewarded[_season][__referee] = _usdSeasonAccountRewarded[_season][__referee].add(__usdReward); _weiSeasonAccountRewarded[_season][__referee] = _weiSeasonAccountRewarded[_season][__referee].add(__weiReward); _usdSeasonAccountReferrals[_season][__referee] = _usdSeasonAccountReferrals[_season][__referee].add(__usd); _weiSeasonAccountReferrals[_season][__referee] = _weiSeasonAccountReferrals[_season][__referee].add(__wei); _vokenSeasonAccountReferrals[_season][__referee] = _vokenSeasonAccountReferrals[_season][__referee].add(__voken); _accountVokenReferrals[__referee] = _accountVokenReferrals[__referee].add(__voken); if (i == 0) { _vokenSeasonAccountReferral[_season][__referee] = _vokenSeasonAccountReferral[_season][__referee].add(__voken); _accountVokenReferral[__referee] = _accountVokenReferral[__referee].add(__voken); } } } } /** * @dev Mint Voken issued. */ function _mintVokenIssued(uint256 amount) private { // Global _vokenIssued = _vokenIssued.add(amount); _vokenIssuedTxs = _vokenIssuedTxs.add(1); // Account _accountVokenIssued[msg.sender] = _accountVokenIssued[msg.sender].add(amount); // Stage _stageVokenIssued[_stage] = _stageVokenIssued[_stage].add(amount); // Season _seasonVokenIssued[_season] = _seasonVokenIssued[_season].add(amount); _vokenSeasonAccountIssued[_season][msg.sender] = _vokenSeasonAccountIssued[_season][msg.sender].add(amount); // Mint assert(_VOKEN.mint(msg.sender, amount)); } /** * @dev Mint Voken bonus. */ function _mintVokenBonus(uint256 amount) private { // Global _vokenBonus = _vokenBonus.add(amount); _vokenBonusTxs = _vokenBonusTxs.add(1); // Account _accountVokenBonus[msg.sender] = _accountVokenBonus[msg.sender].add(amount); // Stage _stageVokenBonus[_stage] = _stageVokenBonus[_stage].add(amount); // Season _seasonVokenBonus[_season] = _seasonVokenBonus[_season].add(amount); _vokenSeasonAccountBonus[_season][msg.sender] = _vokenSeasonAccountBonus[_season][msg.sender].add(amount); // Mint with allocation Allocations.Allocation memory __allocation; __allocation.amount = amount; __allocation.timestamp = now; _allocations[msg.sender].push(__allocation); assert(_VOKEN.mintWithAllocation(msg.sender, amount, address(this))); } /** * @dev Returns the reserved amount of VOKEN by `account`. */ function reservedOf(address account) public view returns (uint256) { Allocations.Allocation[] memory __allocations = _allocations[account]; uint256 __len = __allocations.length; if (__len > 0) { uint256 __vokenIssued = _accountVokenIssued[account]; uint256 __vokenBonus = _accountVokenBonus[account]; uint256 __vokenReferral = _accountVokenReferral[account]; uint256 __vokenBalance = _VOKEN.balanceOf(account); // balance fixed, by Voken issued. if (__vokenIssued < __vokenBalance) { __vokenBalance = __vokenBalance.sub(__vokenIssued); } else { __vokenBalance = 0; } // balance fixed, by Voken bonus. if (__vokenBonus < __vokenBalance) { __vokenBalance = __vokenBalance.sub(__vokenBonus); } else { __vokenBalance = 0; } uint256 __reserved; for (uint256 i = 0; i < __len; i++) { // Voken reserved. Allocations.Allocation memory __allocation = __allocations[i]; __reserved = __reserved.add(__allocation.amount); if (now >= __allocation.timestamp.add(90 days)) { // default: 180 days. uint256 __distance = 180 days; // shorten the distance, by Voken referral, at least 120 days. if (__vokenReferral > __allocation.amount) { __distance = __distance.sub(__vokenReferral.div(__allocation.amount).mul(1 days)); if (__distance > 120 days) { __distance = 120 days; } } // shorten the distance, by Voken holding if (__vokenBalance > __allocation.amount) { __distance = __distance.sub(__vokenBalance.div(__allocation.amount).mul(30 days)); } // at least: 90 days if (__distance > 90 days) { __distance = 90 days; } // calc reserved uint256 __timestamp = __allocation.timestamp.add(__distance); if (now > __timestamp) { uint256 __passed = now.sub(__timestamp).div(1 days).add(1); if (__passed > 30) { __reserved = __reserved.sub(__allocation.amount); } else { __reserved = __reserved.sub(__allocation.amount.mul(__passed).div(30)); } } } } return __reserved; } return 0; } }
USD => voken, by `usdAmount`./
function _usd2voken(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1000000).div(_vokenUsdPrice); }
14,101,999
./full_match/43114/0x4c28f48448720e9000907BC2611F73022fdcE1fA/sources/contracts/router.sol
SWAP requires the initial amount to have already been sent to the first pair
function _swap( uint256[] memory amounts, address[] memory path, address _to ) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = UniswapV2Library.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } }
4,605,692
pragma solidity 0.5.7; contract QuotationMock { address authQuoteEngine; constructor(address _authQuoteEngine) public { authQuoteEngine = _authQuoteEngine; } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySign( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA, uint8 _v, bytes32 _r, bytes32 _s ) public view returns(bool) { require(smaratCA != address(0)); // require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time"); bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA ) public view returns(bytes32) { return keccak256( abi.encodePacked( coverDetails[0], curr, coverPeriod, smaratCA, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == authQuoteEngine); } }
Verifies signature. hash order hash v argument from vrs hash. r argument from vrs hash. s argument from vrs hash./
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == authQuoteEngine); }
5,443,202
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import './Administration.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; /// @author Jan Turk /// @title Praise contract Praise{ using SafeMath for uint256; Administration administration; bool public stopped; uint256 public firstGrowth; uint256 public secondGrowth; mapping (address => Users) users; enum Stage { Seedling, Shrub, Tree } struct Users{ uint256 totalNumberOfPraises; Stage stage; mapping (uint256 => Praises) praises; } struct Praises{ address praiseGiver; string praise; } /// @notice Event to notify that operation has been stopped /// @param executedBy the address of the admin that executed the pause of operation event OperationStopped(address indexed executedBy); /// @notice Event to notify that operation has been resumed /// @param executedBy the address of the admin that executed the resumal of operation event OperationResumed(address indexed executedBy); /// @notice Event to notify that first growth threshold has been updated /// @param newGrowthThreshold new growth threshold value event FirstGrowthThresholdUpdated(uint256 newGrowthThreshold); /// @notice Event to notify that second growth threshold has been updated /// @param newGrowthThreshold new growth threshold value event SecondGrowthThresholdUpdated(uint256 newGrowthThreshold); /// @notice Event to notify that new user has reached Seedling state /// @param user user that reached the state event NewSeedling(address indexed user); /// @notice Event to notify that new user has reached Shrub state /// @param user user that reached the state event UserGrowthToShrub(address indexed user); /// @notice Event to notify that new user has reached Tree state /// @param user user that reached the state event UserGrowthToTree(address indexed user); /// @notice Event to notify that new praise has been issued /// @param praiseGiver user that gave the praise /// @param praiseReceiver user that received the praise /// @param praise praise that was given event NewPraise(address indexed praiseGiver, address indexed praiseReceiver, string praise); /// @notice only allows execution it the contract isn't stopped modifier onlyWhenOperational{ require(!stopped); _; } /// @notice only allows execution it the contract is stopped modifier onlyWhenStopped{ require(stopped); _; } /// @notice only allows execution it the caller is contract owner modifier onlyOwner{ require(administration.checkOwnership(msg.sender)); _; } /// @notice only allows execution it the caller is contract owner or admin modifier onlyAdmin{ require(administration.checkAdministatorship(msg.sender)); _; } /// @notice only allows execution it the caller is contract owner, admin or registered user modifier onlyRegisteredUser{ require(administration.checkRegisteredUser(msg.sender)); _; } /// @notice constructor of the smart contract /// @param administrationAddress address of the Administration smart contract /// @param initialFirstGrowthThreshold value of the initial first growth threshold /// @param initialSecondGrowthThreshold value of the initial second growth threshold constructor ( address administrationAddress, uint256 initialFirstGrowthThreshold, uint256 initialSecondGrowthThreshold ) public { administration = Administration(administrationAddress); administration.initialRegistration(msg.sender); firstGrowth = initialFirstGrowthThreshold; secondGrowth = initialSecondGrowthThreshold; } /// @notice used to view user praise data /// @param _user address of the user whoose data we are looking at /// @return totalNumberOfPraises number of praises that the user received /// @return Stage stage that the user reached function viewUserPraiseData( address _user ) public view returns( uint256 totalNumberOfPraises, Stage ) { return( users[_user].totalNumberOfPraises, users[_user].stage ); } /// @notice used to view user's praise /// @param _user address of the user whoose data we are looking at /// @param _praiseId ID of the praise we are retrieving /// @return praiseGiver user that gave praise /// @return praise text explaining the praise function viewPraise( address _user, uint256 _praiseId ) public view returns( address praiseGiver, string memory praise ) { return( users[_user].praises[_praiseId].praiseGiver, users[_user].praises[_praiseId].praise ); } /// @notice used to stop the operation of the contract /// @return successful execution of the function function emergencyStop() public onlyWhenOperational onlyAdmin returns(bool){ require(toggleOperation()); return true; } /// @notice used to resume the operation of the contract /// @return successful execution of the function function resumeOperation() public onlyWhenStopped onlyAdmin returns(bool){ require(toggleOperation()); return true; } /// @notice used to transfer ownership of the contract /// @param _newOwner address to receive the ownership of the contract /// @return successful executipn of the contract function transferOwnership(address _newOwner) public onlyOwner returns(bool){ require(administration.transferOwnership(msg.sender, _newOwner)); return true; } /// @notice used to appoin administrator of the contract /// @param _admin address to receive the administratorship of the contract /// @return successful executipn of the contract function appointAdmin(address _admin) public onlyOwner returns(bool){ require(administration.appointAdmin(msg.sender, _admin)); return true; } /// @notice used to demote administrator of the contract /// @param _admin address to have the administratorship of the contract revoked /// @return successful executipn of the contract function demoteAdmin(address _admin) public onlyOwner returns(bool){ require(administration.demoteAdmin(msg.sender, _admin)); return true; } /// @notice used to register user of the contract /// @param _user address to receive the registered user rights of the contract /// @return successful executipn of the contract function registerUser(address _user) public onlyAdmin returns(bool){ require(administration.registerUser(msg.sender, _user)); if(users[_user].totalNumberOfPraises == 0){ users[_user].stage = Stage.Seedling; emit NewSeedling(_user); } return true; } /// @notice used to unregister user of the contract /// @param _user address to loose the registered user rights of the contract /// @return successful executipn of the contract function unregisterUser(address _user) public onlyAdmin returns(bool){ require(administration.unregisterUser(msg.sender, _user)); return true; } /// @notice used to set new growth thresholds /// @dev if input value is set to 0, then the threshold value is not updated /// @param _firstGrowth value to be set for first growth threshold /// @param _secondGrowth value to be set for second growth threshold /// @return successful execution of the contract function setGrowthThresholds( uint256 _firstGrowth, uint256 _secondGrowth ) public onlyAdmin returns(bool) { require( _secondGrowth > _firstGrowth || (_secondGrowth == 0 && _firstGrowth < secondGrowth) ); if(_firstGrowth != 0 && _firstGrowth != firstGrowth){ firstGrowth = _firstGrowth; emit FirstGrowthThresholdUpdated(_firstGrowth); } if(_secondGrowth != 0 && _secondGrowth != secondGrowth){ secondGrowth = _secondGrowth; emit SecondGrowthThresholdUpdated(_secondGrowth); } return true; } /// @notice used to force the update od the stage of the user is the growth params have been changed and the user stage should be higher /// @param _user address that has to have stage updated /// @return successful execution of the function function forceUpdateOfUserStage(address _user) public onlyAdmin returns(bool){ require(updateUserStage(_user)); return true; } /// @notice used to give praise from one user to another /// @dev user can not give praise to self /// @dev usregistered users can not receive or give praises /// @param _user address to receive praise /// @param _praise text explaining the praise /// @return successful execution of the contract function givePraise( address _user, string memory _praise ) public onlyRegisteredUser onlyWhenOperational returns(bool) { require(msg.sender != _user); require(administration.checkRegisteredUser(_user)); users[_user].praises[users[_user].totalNumberOfPraises].praiseGiver = msg.sender; users[_user].praises[users[_user].totalNumberOfPraises].praise = _praise; users[_user].totalNumberOfPraises = users[_user].totalNumberOfPraises.add(1); emit NewPraise(msg.sender, _user, _praise); require(updateUserStage(_user)); return true; } /// @notice toggles the operation stage of the contract /// @return successful execution of the contract function toggleOperation() internal returns(bool){ stopped = !stopped; return true; } /// @notice used to update the stage of the user /// @dev this is used in multiple other functions and should just ignore users that do not require stage update /// @param _user address that is being checked for stage update /// @return successful execution of the function function updateUserStage(address _user) internal returns(bool){ if(users[_user].stage == Stage.Shrub && users[_user].totalNumberOfPraises >= secondGrowth){ users[_user].stage = Stage.Tree; emit UserGrowthToTree(_user); } else if( users[_user].stage == Stage.Seedling && users[_user].totalNumberOfPraises >= firstGrowth ) { users[_user].stage = Stage.Shrub; emit UserGrowthToShrub(_user); } return true; } }
used to stop the operation of the contract return successful execution of the function
function emergencyStop() public onlyWhenOperational onlyAdmin returns(bool){ require(toggleOperation()); return true; }
6,353,379
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract KeepWatchCrew is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; enum SaleModes { NONE, VIP_PRESALE, PUBLIC_SALE } string public notRevealedUri; string private baseTokenURI; SaleModes public saleMode = SaleModes.NONE; mapping(address => bool) public presaleAddresses; mapping(address => bool) public vipAddresses; mapping(address => uint256) mintedAmounts; bool public revealed = false; bool public paused = false; uint256 public constant MAX_ELEMENTS = 6969; uint256 public PRICE = 69 * (10**15); // 0.069 ETH uint256 public DISCOUNT_PRICE = 59 * (10**15); // 0.059 ETH uint256 public maxVIPMint = 1; uint256 public maxPresaleMint = 4; uint256 public maxPublicMint = 8; uint256 public publicSaleDate = 1639695600; address payable public constant payoutAddress = payable(0x032b023b216Dc3b9A30975ABf1f51De92a764a46); event CreateKWC(uint256 indexed id); constructor(string memory baseURI, string memory _notRevealedUri) ERC721("KeepWatchCrew", "KWC") { setBaseURI(baseURI); // Dummy IPFS metadata JSON URI for before reveal setNotRevealedURI(_notRevealedUri); // Pause minting by default pause(true); } function isVIP(address _user) public view returns (bool) { return vipAddresses[_user]; } function isInPresale(address _user) public view returns (bool) { return presaleAddresses[_user]; } function totalMint(address _user) public view returns (uint256) { return mintedAmounts[_user]; } function _mintAnElement(address _to) internal { uint256 id = totalSupply() + 1; _safeMint(_to, id); emit CreateKWC(id); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = baseTokenURI; return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), ".json" ) ) : ""; } function mint(uint256 _count) public payable { require(!paused, "Pausable: paused"); uint256 total = totalSupply(); address sender = _msgSender(); require(_count > 0); require(total <= MAX_ELEMENTS, "Sale end"); require(total + _count <= MAX_ELEMENTS, "Max limit"); // Nobody can mint except the contract owner if it's in default mode if (saleMode == SaleModes.NONE) { require(sender == owner()); } uint256 mintedAmount = mintedAmounts[sender]; bool isInPresaleList = isInPresale(sender); bool isInVIP = isVIP(sender); if (saleMode == SaleModes.VIP_PRESALE) { if (sender != owner()) { require(isInVIP || isInPresaleList); if (isInVIP) { if (mintedAmount == 0) { require(_count == maxVIPMint, "You can't mint more than allowed number of tokens"); } else { require(isInPresaleList, "You are not allowed to mint"); uint256 maxMint = maxVIPMint + maxPresaleMint; require(_count + mintedAmount <= maxMint, "You can't mint more than allowed number of tokens"); require(msg.value >= DISCOUNT_PRICE.mul(_count), "Value below price"); } } else { require(_count + mintedAmount <= maxPresaleMint, "You can't mint more than allowed number of tokens"); require(msg.value >= DISCOUNT_PRICE.mul(_count), "Value below price"); } } } if (saleMode == SaleModes.PUBLIC_SALE) { if (sender != owner()) { require(_count <= maxPublicMint, "Number of mintable tokens limited per wallet"); require(msg.value >= PRICE.mul(_count), "Value below price"); } } for (uint256 i = 0; i < _count; i++) { _mintAnElement(sender); mintedAmounts[sender] += 1; } } // Only owner // Change Mode function activateNextSaleMode() external onlyOwner { if (saleMode == SaleModes.NONE) { saleMode = SaleModes.VIP_PRESALE; } else if (saleMode == SaleModes.VIP_PRESALE) { saleMode = SaleModes.PUBLIC_SALE; } } // Add users to Presale list function addUsersToPresaleList(address[] calldata _users) external onlyOwner { for(uint256 i = 0; i < _users.length; i++) { address user = _users[i]; require(user != address(0), "Null Address"); presaleAddresses[user] = true; } } function removeUsersFromPresaleList(address[] calldata _users) external onlyOwner { for(uint256 i = 0; i < _users.length; i++) { address user = _users[i]; require(user != address(0), "Null Address"); presaleAddresses[user] = false; } } // Add users to VIP list function addUsersToVIPList(address[] calldata _users) external onlyOwner { for(uint256 i = 0; i < _users.length; i++) { address user = _users[i]; require(user != address(0), "Null Address"); vipAddresses[user] = true; } } function removeUsersFromVIPList(address[] calldata _users) external onlyOwner { for(uint256 i = 0; i < _users.length; i++) { address user = _users[i]; require(user != address(0), "Null Address"); vipAddresses[user] = false; } } // Reveals real metadata for NFTs function reveal() public onlyOwner { revealed = true; } // Pause/unpause contract function pause(bool val) public onlyOwner { paused = val; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function setNotRevealedURI(string memory _notRevealedUri) public onlyOwner { notRevealedUri = _notRevealedUri; } function updateMaxPresaleAmount(uint256 _amount) external onlyOwner { maxPresaleMint = _amount; } function updateMaxPublicAmount(uint256 _amount) external onlyOwner { maxPublicMint = _amount; } function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0); payoutAddress.transfer(balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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; 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; /** * @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 "../../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 "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Pause/unpause contract
function pause(bool val) public onlyOwner { paused = val; }
1,218,180
./full_match/3/0x9249d90433D2B6071EA7f76c125F23Ba34b52A56/sources/browser/minner/minner.sol
swap t: trade type quantity: amount check, t == 0 require(finalOut > quantity, "No profit");ETH => token token => ETH require(finalOut > quantity, "No profit");ETH => token token => ETH
function go(address tokenA, address tokenB, uint quantity, uint t) public auth { uint balance = address(this).balance; require(balance >= quantity, "Insufficient"); (uint reserveA1, uint reserveB1) = UniswapV2Library.getReserves(factory1, tokenA, tokenB); (uint reserveA2, uint reserveB2) = UniswapV2Library.getReserves(factory2, tokenA, tokenB); uint finalOut = 0; if(t == 0) { uint amountOut = UniswapV2Library.getAmountOut(quantity, reserveA1, reserveB1); finalOut = UniswapV2Library.getAmountOut(amountOut, reserveB2, reserveA2); uint deadline = block.timestamp + 1800; address[] memory path = new address[](2); path[0] = tokenA; path[1] = tokenB; address[] memory path1 = new address[](2); path1[0] = tokenB; path1[1] = tokenA; IUniswapV2Router01(router2).swapExactTokensForETH(amountOut, finalOut, path1, address(this), deadline); emit Info(amountOut, finalOut); } else { uint amountOut = UniswapV2Library.getAmountOut(quantity, reserveA2, reserveB2); finalOut = UniswapV2Library.getAmountOut(amountOut, reserveB1, reserveA1); uint deadline = block.timestamp + 1800; address[] memory path = new address[](2); path[0] = tokenA; path[1] = tokenB; address[] memory path1 = new address[](2); path1[0] = tokenB; path1[1] = tokenA; IUniswapV2Router01(router1).swapExactTokensForETH(amountOut, finalOut, path1, address(this), deadline); emit Info(amountOut, finalOut); } }
8,253,005
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./NFTStorage1155.sol"; import "./Libraries/LibShare.sol"; import "./Libraries/LibRoyalty.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "./TokenERC1155.sol"; import "./PNDC_ERC1155.sol"; contract NFTFactoryContract1155 is OwnableUpgradeable, ReentrancyGuardUpgradeable, ERC1155HolderUpgradeable, NFTV1Storage1155 { using Counters for Counters.Counter; // function initialize() initializer public { // OwnableUpgradeable.__Ownable_init(); // ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); // ERC1155HolderUpgradeable.__ERC1155Holder_init(); // } event TokenMetaReturn(LibMeta1155.TokenMeta data, uint256 id); // Change in BuyNFT LibMeta Function function BuyNFT(uint256 _saleId, uint256 _amount) external payable nonReentrant { LibMeta1155.TokenMeta memory meta = _tokenMeta[_saleId]; LibShare.Share[] memory royalties = LibRoyalty.retrieveRoyalty( meta.collectionAddress, PNDC1155Address, meta.tokenId ); require(meta.status); require(msg.sender != address(0) && msg.sender != meta.currentOwner); require(!meta.bidSale); require(meta.numberOfTokens >= _amount); require(msg.value >= (meta.price * _amount)); LibMeta1155.transfer(_tokenMeta[_saleId], _amount); uint256 sum = msg.value; uint256 val = msg.value; uint256 fee = msg.value / 100; for(uint256 i = 0; i < royalties.length; i ++) { uint256 amount = (royalties[i].value * val ) / 10000; (bool royalSuccess, ) = payable(royalties[i].account).call{ value: amount }(""); require(royalSuccess, "Transfer failed"); sum = sum - amount; } (bool isSuccess, ) = payable(meta.currentOwner).call{ value: (sum - fee) }(""); require(isSuccess, "Transfer failed"); (bool feeSuccess, ) = payable(feeAddress).call{ value: fee }(""); require(feeSuccess, "Fee Transfer failed"); ERC1155(meta.collectionAddress).safeTransferFrom( address(this), msg.sender, meta.tokenId, _amount, "" ); } function sellNFT(address _collectionAddress, uint256 _tokenId, uint256 _price, uint256 _amount) external nonReentrant { require(_collectionAddress != address(0)); uint256 bal = ERC1155(_collectionAddress).balanceOf(msg.sender, _tokenId); require(bal >= _amount); _tokenIdTracker.increment(); //needs approval on frontend ERC1155(_collectionAddress).safeTransferFrom(msg.sender, address(this), _tokenId, _amount, ""); LibMeta1155.TokenMeta memory meta = LibMeta1155.TokenMeta( _collectionAddress, _tokenId, _amount, _price, true, false, true, msg.sender ); _tokenMeta[_tokenIdTracker.current()] = meta; emit TokenMetaReturn(meta, _tokenIdTracker.current()); } function cancelSale(uint256 _saleId) external nonReentrant{ require(msg.sender == _tokenMeta[_saleId].currentOwner); require(_tokenMeta[_saleId].status); _tokenMeta[_saleId].status = false; ERC1155(_tokenMeta[_saleId].collectionAddress).safeTransferFrom( address(this), _tokenMeta[_saleId].currentOwner, _tokenMeta[_saleId].tokenId, _tokenMeta[_saleId].numberOfTokens, "" ); } }
function initialize() initializer public { OwnableUpgradeable.__Ownable_init(); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); ERC1155HolderUpgradeable.__ERC1155Holder_init(); } Change in BuyNFT LibMeta Function
{ using Counters for Counters.Counter; event TokenMetaReturn(LibMeta1155.TokenMeta data, uint256 id); pragma solidity 0.8.2; function BuyNFT(uint256 _saleId, uint256 _amount) external payable nonReentrant { LibMeta1155.TokenMeta memory meta = _tokenMeta[_saleId]; LibShare.Share[] memory royalties = LibRoyalty.retrieveRoyalty( meta.collectionAddress, PNDC1155Address, meta.tokenId ); require(meta.status); require(msg.sender != address(0) && msg.sender != meta.currentOwner); require(!meta.bidSale); require(meta.numberOfTokens >= _amount); require(msg.value >= (meta.price * _amount)); LibMeta1155.transfer(_tokenMeta[_saleId], _amount); uint256 sum = msg.value; uint256 val = msg.value; uint256 fee = msg.value / 100; for(uint256 i = 0; i < royalties.length; i ++) { uint256 amount = (royalties[i].value * val ) / 10000; require(royalSuccess, "Transfer failed"); sum = sum - amount; } require(isSuccess, "Transfer failed"); require(feeSuccess, "Fee Transfer failed"); ERC1155(meta.collectionAddress).safeTransferFrom( address(this), msg.sender, meta.tokenId, _amount, "" ); } function BuyNFT(uint256 _saleId, uint256 _amount) external payable nonReentrant { LibMeta1155.TokenMeta memory meta = _tokenMeta[_saleId]; LibShare.Share[] memory royalties = LibRoyalty.retrieveRoyalty( meta.collectionAddress, PNDC1155Address, meta.tokenId ); require(meta.status); require(msg.sender != address(0) && msg.sender != meta.currentOwner); require(!meta.bidSale); require(meta.numberOfTokens >= _amount); require(msg.value >= (meta.price * _amount)); LibMeta1155.transfer(_tokenMeta[_saleId], _amount); uint256 sum = msg.value; uint256 val = msg.value; uint256 fee = msg.value / 100; for(uint256 i = 0; i < royalties.length; i ++) { uint256 amount = (royalties[i].value * val ) / 10000; require(royalSuccess, "Transfer failed"); sum = sum - amount; } require(isSuccess, "Transfer failed"); require(feeSuccess, "Fee Transfer failed"); ERC1155(meta.collectionAddress).safeTransferFrom( address(this), msg.sender, meta.tokenId, _amount, "" ); } (bool royalSuccess, ) = payable(royalties[i].account).call{ value: amount }(""); (bool isSuccess, ) = payable(meta.currentOwner).call{ value: (sum - fee) }(""); (bool feeSuccess, ) = payable(feeAddress).call{ value: fee }(""); function sellNFT(address _collectionAddress, uint256 _tokenId, uint256 _price, uint256 _amount) external nonReentrant { require(_collectionAddress != address(0)); uint256 bal = ERC1155(_collectionAddress).balanceOf(msg.sender, _tokenId); require(bal >= _amount); _tokenIdTracker.increment(); ERC1155(_collectionAddress).safeTransferFrom(msg.sender, address(this), _tokenId, _amount, ""); LibMeta1155.TokenMeta memory meta = LibMeta1155.TokenMeta( _collectionAddress, _tokenId, _amount, _price, true, false, true, msg.sender ); _tokenMeta[_tokenIdTracker.current()] = meta; emit TokenMetaReturn(meta, _tokenIdTracker.current()); } function cancelSale(uint256 _saleId) external nonReentrant{ require(msg.sender == _tokenMeta[_saleId].currentOwner); require(_tokenMeta[_saleId].status); _tokenMeta[_saleId].status = false; ERC1155(_tokenMeta[_saleId].collectionAddress).safeTransferFrom( address(this), _tokenMeta[_saleId].currentOwner, _tokenMeta[_saleId].tokenId, _tokenMeta[_saleId].numberOfTokens, "" ); } }
6,434,012
./full_match/420/0x84932aa12B7ae3641bd5A77fAaE20948a9997f08/sources/contracts/messaging/connectors/optimism/OptimismSpokeConnector.sol
Sends `outboundRoot` to root manager on l1/
function _sendMessage(bytes memory _data) internal override { bytes memory _calldata = abi.encodeWithSelector(Connector.processMessage.selector, _data); OptimismAmb(AMB).sendMessage(mirrorConnector, _calldata, uint32(mirrorGas)); }
13,225,380
./full_match/42/0x068402afAFb8a2ac706557F2794Bbc370cC056f9/sources/contracts/comp_v3/UNIV3Flash.sol
Liquidate a Compound user with a flash swap _borrower (address): the Compound user to liquidate _repayCToken (address): a CToken for which the user is in debt _seizeCToken (address): a CToken for which the user has a supply balance _amount (uint): the amount (specified in units of _repayCToken.underlying) to flash loan and pay off/require(_amount>0,"amount = 0");/pair = UniswapV2Library.pairFor(FACTORY, r, WETH); pair = UniswapV2Library.pairFor(FACTORY, WETH, CErc20Storage(_seizeCToken).underlying()); r = CErc20Storage(_repayCToken).underlying(); uint maxBorrow; (maxBorrow, , pair) = UniswapV2Library.getReservesWithPair(FACTORY, r, CErc20Storage(_seizeCToken).underlying()); if (_amount 100000 > maxBorrow SLIPPAGE_THRESHOLD_FACT) pair = IUniswapV2Factory(FACTORY).getPair(r, WETH);
function liquidate(address _borrower, address _repayCToken, address _seizeCToken, uint _amount, uint24 _poolFee) public { PoolAddress.PoolKey memory poolKey; address r; require(_amount>100,"amount = 100"); require(_amount>1000,"amount = 1000"); require(_amount>10000,"amount = 10000"); require(_amount>100000,"amount = 100000"); if (_repayCToken == _seizeCToken || _seizeCToken == CETH) { r = CErc20Storage(_repayCToken).underlying(); poolKey = PoolAddress.getPoolKey(r, WETH, _poolFee); } else if (_repayCToken == CETH) { r = WETH; poolKey = PoolAddress.getPoolKey(r, CErc20Storage(_seizeCToken).underlying(), _poolFee); } else { r = CErc20Storage(_repayCToken).underlying(); poolKey = PoolAddress.getPoolKey(r, CErc20Storage(_seizeCToken).underlying(), _poolFee); } uint amount0 = IUniswapV2Pair(pair).token0() == r ? _amount : 0; uint amount1 = IUniswapV2Pair(pair).token1() == r ? _amount : 0; IUniswapV2Pair(pair).swap(amount0, amount1, address(this), data); address(this), poolKey.token0 == r ? _amount : 0, poolKey.token1 == r ? _amount : 0, abi.encode( CompCallbackData({ borrower: _borrower, repayCToken: _repayCToken, repayAmount: _amount, seizeCToken: _seizeCToken, seizeAmount: 0, poolKey: poolKey, payer: msg.sender }) ) ); }
9,579,363
./full_match/43114/0xD87fF8b52Dc218d436b8190261c98CE7714B145c/sources/JoeLendingLiquidator.sol
1. get all borrowed token infos 2. get all supply token infos 3. find max borrow and max supply the final repayAmount = min(maxBorrowed 0.5, maxSupplied)/
function liquidateOneAccount(address account) public { AccountLimits memory vars = joeLensView.getAccountLimits(address(joetroller), account); require(vars.shortfall > 0, 'shortfall'); address[] memory jTokens = joetroller.getAssetsIn(account); JTokenBalances[] memory bals = joeLensView.jTokenBalancesAll(jTokens, account); address maxBorrowToken; uint256 maxBorrowValue; address maxSupplyToken; uint256 maxSupplyValue; for (uint256 i = 0; i < bals.length; i++) { JTokenBalances memory b = bals[i]; if (maxBorrowValue < b.borrowValueUSD) { maxBorrowValue = b.borrowValueUSD; maxBorrowToken = b.jToken; } if (maxSupplyValue < b.supplyValueUSD) { maxSupplyValue = b.supplyValueUSD; maxSupplyToken = b.jToken; } } uint256 borrowUTokenPrice = oracle.getUnderlyingPrice(maxBorrowToken); uint256 decimals = IERC20Ex(IJToken(maxBorrowToken).underlying()).decimals(); uint256 maxBorrowAmt = maxLiquidateValue.mul(1e18).div(borrowUTokenPrice); address receiverAddress = address(this); address[] memory assets = new address[](1); assets[0] = IJToken(maxBorrowToken).underlying(); uint256[] memory amounts = new uint256[](1); amounts[0] = maxBorrowAmt; uint256[] memory modes = new uint256[](1); modes[0] = 0; address onBehalfOf = address(this); uint16 referralCode = 0; LENDING_POOL.flashLoan( receiverAddress, assets, amounts, modes, onBehalfOf, data, referralCode ); IERC20(assets[0]).transfer(vault, balOfRemain); }
16,383,507
// contracts/GLDToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // import "./contracts/token/ERC20/ERC20.sol"; contract Sktl20 is ERC20 { uint256 public constant scaling = 1000000000000000000; // 10^18 uint256 public totalTokens = 0; address internal _owner; // owner who can mint address internal _vault; // vault address to store the rewards & donations uint256 public scaledRewardPerToken; // Amount of total rewards per token ever given, scaled by scaling factor mapping(address => uint256) public scaledRewardCreditedTo; // Amount of scaled reward per token credited to account thus far uint256 public scaledRemainder = 0; bool private _enable_hook = true; constructor(uint256 initialSupply) ERC20("Skytale", "sktb") { _owner = _msgSender(); _vault = _msgSender(); _mint(_vault, initialSupply); totalTokens = initialSupply; } function reward_balance(address account) public view virtual returns (uint256) { // Calculate scaled value owed per token for account uint256 scaledOwed = scaledRewardPerToken - scaledRewardCreditedTo[account]; // Return unclaimed portion of total rewards for account // TODO - Does balanceOf return tokens or wei? What aboouot reward_balance? return (balanceOf[account] * scaledOwed) / scaling; } // Check for and claim any unclaimed account reward balance function _update(address account) internal { uint256 owed = reward_balance(account); if (owed > 0) { // this is _transfer() without hook, may need to handle revert _enable_hook = false; scaledRewardCreditedTo[account] = scaledRewardPerToken; _transfer(_vault, account, owed); _enable_hook = true; } } function set_owner(address new_owner) public virtual returns (bool) { require( _msgSender() == _owner, "Only current owner can assign a new owner" ); // todo to check the validity of new_owner _owner = new_owner; return true; } function set_vault(address new_vault) public virtual returns (bool) { require( _msgSender() == _owner, "Only current owner can assign a new owner" ); // todo to check the validity of new_vault _transfer(_vault, new_vault, balanceOf(_vault)); _vault = new_vault; return true; } // Before any transfer, claim rewards for the source and destination accts function _beforeTokenTransfer( address from, address to, uint256 value ) internal virtual override { super._beforeTokenTransfer(from, to, value); if (!_enable_hook) return; if (from == address(0)) // minting return; _update(from); _update(to); } function _afterTokenTransfer( address from, address to, uint256 value ) internal virtual override { super._afterTokenTransfer(from, to, value); if (!_enable_hook) return; if (from == address(0)) // miniting return; } function rewards(uint256 amount) public { require(_msgSender() == _owner, "Only owner can create new rewards"); // scale the deposit and add the previous remainder uint256 scaledAvailable = (amount * scaling) + scaledRemainder; // Calculate scaled award per token, save remainder scaledRewardPerToken += scaledAvailable / totalTokens; scaledRemainder = scaledAvailable % totalTokens; _mint(_vault, amount); totalTokens += amount; scaledRewardCreditedTo[_vault] = scaledRewardPerToken; } function withdraw() public { require( reward_balance(_msgSender()) > 0, "No rewards left to withdraw" ); _update(_msgSender()); } }
Before any transfer, claim rewards for the source and destination accts minting
function _beforeTokenTransfer( address from, address to, uint256 value ) internal virtual override { super._beforeTokenTransfer(from, to, value); if (!_enable_hook) return; if (from == address(0)) return; _update(from); _update(to); }
5,380,620
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.8.0; /// @title int256 Logic Utilities /// @author Tyler R. Drury - 19/2/2021, All Rights Reserved /// @notice trivial library for logical or bitwise operations on int256 not provided natively by Solidity. library int256Logic { int256 public constant ZERO = 0x0; //int256 public constant MIN = type(int256).min; //int256 public constant MAX = type(int256).max; function equal( int256 lhs, int256 rhs )internal pure returns( bool ){ //return lhs ^ rhs == 0; return lhs == rhs; } function notEqual( int256 lhs, int256 rhs )internal pure returns( bool ){ //return lhs ^ rhs != 0; return lhs != rhs; } function notEqualToZero( int256 lhs )internal pure returns( bool ){ return lhs != ZERO; } function _and( int256 lhs, int256 rhs )internal pure returns( int256 ret ){ assembly{ ret := and(lhs, rhs) } } function _or( int256 lhs, int256 rhs )internal pure returns( int256 ret ){ assembly{ ret := or(lhs, rhs) } } function _xor( int256 lhs, int256 rhs )internal pure returns( int256 ret ){ assembly{ ret := xor(lhs, rhs) } } //function not( //int256 lhs //)public pure returns( //int256 ret //){ //ret := not(lhs) //} /** * Greater Than > operatiors */ function greaterThan( int256 lhs, int256 rhs )internal pure returns( bool ret ){ assembly{ ret := sgt(lhs, rhs) } } function greaterThanOrEqual( int256 lhs, int256 rhs )internal pure returns( bool ){ return lhs >= rhs; } function greaterThanZero( int256 lhs )internal pure returns( bool ret ){ assembly{ ret := sgt(lhs,0) } } function greaterThanOrEqualToZero( int256 lhs )internal pure returns( bool ){ return greaterThanOrEqual(lhs, ZERO); } /** * Less Than < operatiors */ function lessThan( int256 lhs, int256 rhs )internal pure returns( bool ret ){ assembly{ ret := slt(lhs,rhs) } } function lessThanOrEqual( int256 lhs, int256 rhs )internal pure returns( bool ){ return lhs <= rhs; } function lessThanZero( int256 lhs )internal pure returns( bool ret ){ assembly{ ret := slt(lhs,0) } } function lessThanOrEqualToZero( int256 lhs ) public pure returns( bool ){ return lessThanOrEqual(lhs, ZERO); } //function lessThanMax( //int256 lhs //) public pure returns( //bool //){ //assembly{ //ret := slt(lhs, MAX) //} //} //function greaterThanMin( //int256 lhs //) public pure //returns(bool) //{ //assembly{ //ret := sgt(lhs, MIN) //} //} /// @return true if `lhs` is within the inclusive range between `min` and `max`, otherwise false function inRange( int256 lhs, int256 min, int256 max )public pure returns( bool ){ require(max > min, 'min cannot be > max'); return greaterThanOrEqual(lhs, min) && lessThanOrEqual(lhs, max); } /// @return true `lhs` is within the exclusive range between `min` and `max`, otherwise false function inXRange( int256 lhs, int256 min, int256 max )public pure returns( bool ){ require(max > min, 'min cannot be > max'); return greaterThan(lhs, min) && lessThan(lhs, max); } }
return true `lhs` is within the exclusive range between `min` and `max`, otherwise false
function inXRange( int256 lhs, int256 min, int256 max )public pure returns( bool ){ require(max > min, 'min cannot be > max'); return greaterThan(lhs, min) && lessThan(lhs, max); }
5,547,933
pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; interface SombraNFT { function minter(uint256 id) external returns (address); } // Not to be confused with the actual WETH contract. This is a simple // contract to keep track of ETH/BNB the user is owned by the contract. // // The user can withdraw it at any moment, it's not a token, hence it's not // transferable. The marketplace will automatically try to refund the ETH to // the user (e.g outbid, NFT sold) with a gas limit. This is simply backup // when the ETH/BNB could not be sent to the user/address. For example, if // the user is a smart contract that uses a lot of gas on it's payable. contract WrappedETH is ReentrancyGuard { mapping(address => uint256) public wethBalance; function claimBNB() external nonReentrant { uint256 refund = wethBalance[msg.sender]; wethBalance[msg.sender] = 0; msg.sender.call{value: refund}; } // claimBNBForUser tries to payout the user's owned balance with // a gas limit. function claimBNBForUser(address user) external nonReentrant { uint256 refund = wethBalance[user]; wethBalance[user] = 0; user.call{value: refund, gas: 3500}; } // rewardBNBToUserAndClaim increases the user's internal BNB balance and // tries to payout their entire balance safely. function rewardBNBToUserAndClaim(address user, uint256 amount) internal { wethBalance[user] += amount; try this.claimBNBForUser(user) {} catch {} } function rewardBNBToUser(address user, uint256 amount) internal { wethBalance[user] += amount; } } contract Buyback { // Uniswap V2 Router address for buyback functionality. IUniswapV2Router02 public uniswapV2Router; // Keep store of the WETH address to save on gas. address WETH; address constant burnAddress = address(0x000000000000000000000000000000000000dEaD); uint256 ethToBuybackWith = 0; event UniswapRouterUpdated( address newAddress ); event SombraBuyback( uint256 ethSpent ); function updateBuybackUniswapRouter(address newRouterAddress) internal { uniswapV2Router = IUniswapV2Router02(newRouterAddress); WETH = uniswapV2Router.WETH(); emit UniswapRouterUpdated(newRouterAddress); } function buybackSombra() external { require(msg.sender == address(this), "can only be called by the contract"); address[] memory path = new address[](2); path[0] = WETH; path[1] = address(this); uint256 amount = ethToBuybackWith; ethToBuybackWith = 0; uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, // accept any amount of Tokens path, burnAddress, // Burn the buyback tokens (@note: subject to change) block.timestamp ); emit SombraBuyback(amount); } function swapETHForTokens(uint256 amount) internal { ethToBuybackWith += amount; // 500k gas is more than enough. try this.buybackSombra{gas: 500000}() {} catch {} } } contract SombraMarketplace is ReentrancyGuard, Ownable, WrappedETH, Buyback { // MarketItem consists of buy-now and bid items. // Auction refers to items that can be bid on. // An item can either be buy-now or bid, or both. struct MarketItem { uint256 tokenId; address payable seller; // If purchasePrice is non-0, item can be bought out-right for that price // if bidPrice is non-0, item can be bid upon. uint256 purchasePrice; uint256 bidPrice; uint8 state; uint64 listingCreationTime; uint64 auctionStartTime; // Set when first bid is received. 0 until then. uint64 auctionEndTime; // Initially it is the DURATION of the auction. // After the first bid, it is set to the END time // of the auction. // Defaults to 0. When 0, no bid has been placed yet. address payable highestBidder; } uint8 constant ON_MARKET = 0; uint8 constant SOLD = 1; uint8 constant CANCELLED = 2; // itemsOnMarket is a list of all items, historic and current, on the marketplace. // This includes items all of states, i.e items are never removed from this list. MarketItem[] public itemsOnMarket; // sombraNFTAddress is the address for the Sombra NFT address. address immutable public sombraNFTAddress; // devWalletAddress is the Sombra development address for 10% fees. address constant public devWalletAddress = 0x949d36d76236217D4Fae451000861B535D9500Ab; event AuctionItemAdded( uint256 tokenId, address tokenAddress, uint256 bidPrice, uint256 auctionDuration ); event FixedPriceItemAdded( uint256 id, uint256 tokenId, address tokenAddress, uint256 purchasePrice ); event ItemSold( uint256 id, address buyer, uint256 purchasePrice, uint256 bidPrice ); event HighestBidIncrease( uint256 id, address bidder, uint256 amount, uint256 auctionEndTime ); event PriceReduction( uint256 tokenAddress, uint256 newPurchasePrice, uint256 newBidPrice ); event ItemPulledFromMarket(uint256 id); constructor(address _sombraNFTAddress, address _uniswapRouterAddress) { sombraNFTAddress = _sombraNFTAddress; updateBuybackUniswapRouter(_uniswapRouterAddress); } function updateUniswapRouter(address newRouterAddress) external onlyOwner { updateBuybackUniswapRouter(newRouterAddress); } function isMinter(uint256 id, address target) internal returns (bool) { SombraNFT sNFT = SombraNFT(sombraNFTAddress); return sNFT.minter(id) == target; } function minter(uint256 id) internal returns (address) { SombraNFT sNFT = SombraNFT(sombraNFTAddress); return sNFT.minter(id); } function handleFees(uint256 id, uint256 amount, bool isMinterSale) internal returns (uint256) { uint256 buybackFee; if(!isMinterSale) { // In resale, 5% buyback and 5% to artist. // 90% to seller. buybackFee = amount * 105 / 100; uint256 artistFee = amount * 105 / 100; rewardBNBToUserAndClaim(minter(id), artistFee); amount = amount - artistFee; } else { // When it's the minter selling, they get 80% // 10% to buyback // 10% to SOMBRA dev wallet. buybackFee = amount * 110 / 100; uint256 devFee = amount * 110 / 100; rewardBNBToUserAndClaim(devWalletAddress, devFee); amount = amount - devFee; } swapETHForTokens(buybackFee); return amount - buybackFee; } function createAuctionItem( uint256 tokenId, address seller, uint256 purchasePrice, uint256 startingBidPrice, uint256 biddingTime ) internal { itemsOnMarket.push( MarketItem( tokenId, payable(seller), purchasePrice, startingBidPrice, ON_MARKET, uint64(block.timestamp), uint64(0), uint64(biddingTime), payable(address(0)) ) ); } // purchasePrice is the direct purchasing price. Starting bid price // is the starting price for bids. If purchase price is 0, item cannot // be bought directly. Similarly for startingBidPrice, if it's 0, item // cannot be bid upon. One of them must be non-zero. function listItemOnAuction( address tokenAddress, uint256 tokenId, uint256 purchasePrice, uint256 startingBidPrice, uint256 biddingTime ) external returns (uint256) { IERC721 tokenContract = IERC721(tokenAddress); require(tokenAddress == sombraNFTAddress, "Item must be Sombra NFT"); require(tokenContract.ownerOf(tokenId) == msg.sender, "Missing Item Ownership"); require(tokenContract.getApproved(tokenId) == address(this), "Missing transfer approval"); require(purchasePrice > 0 || startingBidPrice > 0, "Item must have a price"); require(startingBidPrice == 0 || biddingTime > 3600, "Bidding time must be above one hour"); uint256 newItemId = itemsOnMarket.length; createAuctionItem( tokenId, msg.sender, purchasePrice, startingBidPrice, biddingTime ); IERC721(sombraNFTAddress).transferFrom( msg.sender, address(this), tokenId ); if(purchasePrice > 0) { emit FixedPriceItemAdded(newItemId, tokenId, tokenAddress, purchasePrice); } if(startingBidPrice > 0) { emit AuctionItemAdded( tokenId, sombraNFTAddress, startingBidPrice, biddingTime ); } return newItemId; } function buyFixedPriceItem(uint256 id) external payable nonReentrant { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(msg.value >= item.purchasePrice, "Not enough funds sent"); require(item.purchasePrice > 0, "Item does not have a purchase price."); require(msg.sender != item.seller, "Seller can't buy"); item.state = SOLD; IERC721(sombraNFTAddress).safeTransferFrom( address(this), msg.sender, item.tokenId ); uint256 netPrice = handleFees(id, item.purchasePrice, isMinter(id, item.seller)); rewardBNBToUser(item.seller, netPrice); emit ItemSold(id, msg.sender, item.purchasePrice, item.bidPrice); itemsOnMarket[id] = item; // If the user sent excess ETH/BNB, send any extra back to the user. uint256 refundableEther = msg.value - item.purchasePrice; if(refundableEther > 0) { payable(msg.sender).call{value: refundableEther}; } try this.claimBNBForUser(item.seller) {} catch {} } function placeBid(uint256 id) external payable nonReentrant { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(block.timestamp < item.auctionEndTime || item.highestBidder == address(0), "Auction has ended"); if (item.highestBidder != address(0)) { require(msg.value >= item.bidPrice * 105 / 100, "Bid must be 5% higher than previous bid"); } else { require(msg.value >= item.bidPrice, "Too low bid"); // First bid! item.auctionStartTime = uint64(block.timestamp); // item.auctionEnd is the auction duration. Add current time to it // to set it to the end time. item.auctionEndTime += uint64(block.timestamp); } address previousBidder = item.highestBidder; // Return BNB to previous highest bidder. if (previousBidder != address(0)) { rewardBNBToUser(previousBidder, item.bidPrice); } item.highestBidder = payable(msg.sender); item.bidPrice = msg.value; // Extend the auction time by 5 minutes if there is less than 5 minutes remaining. // This is to prevent snipers sniping in the last block, and give everyone a chance // to bid. if ((item.auctionEndTime - block.timestamp) < 300){ item.auctionEndTime = uint64(block.timestamp + 300); } emit HighestBidIncrease(id, msg.sender, msg.value, item.auctionEndTime); itemsOnMarket[id] = item; if (previousBidder != address(0)) { try this.claimBNBForUser(previousBidder) {} catch {} } } function closeAuction(uint256 id) external { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(item.bidPrice > 0, "Item is not on auction."); require(item.highestBidder != address(0), "No bids placed"); require(block.timestamp > item.auctionEndTime, "Auction is still on going"); item.state = SOLD; IERC721(sombraNFTAddress).transferFrom( address(this), item.highestBidder, item.tokenId ); uint256 netPrice = handleFees(id, item.bidPrice, isMinter(id, item.seller)); rewardBNBToUser(item.seller, netPrice); emit ItemSold(id, item.highestBidder, item.purchasePrice, item.bidPrice); try this.claimBNBForUser(item.seller) {} catch {} itemsOnMarket[id] = item; } function reducePrice( uint256 id, uint256 reducedPrice, uint256 reducedBidPrice ) external { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(msg.sender == item.seller, "Only the item seller can trigger a price reduction"); require(block.timestamp >= item.listingCreationTime + 600, "Must wait ten minutes after listing before lowering the listing price"); require(item.highestBidder == address(0), "Cannot reduce price once a bid has been placed"); require(reducedBidPrice > 0 || reducedPrice > 0, "Must reduce price"); if (reducedPrice > 0) { require( item.purchasePrice > 0 && reducedPrice <= item.purchasePrice * 95 / 100, "Reduced price must be at least 5% less than the current price" ); item.purchasePrice = reducedPrice; } if (reducedBidPrice > 0) { require( item.bidPrice > 0 && reducedBidPrice <= item.bidPrice * 95 / 100, "Reduced price must be at least 5% less than the current price" ); item.bidPrice = reducedPrice; } itemsOnMarket[id] = item; emit PriceReduction( id, item.purchasePrice, item.bidPrice ); } function pullFromMarket(uint256 id) external { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(msg.sender == item.seller, "Only the item seller can pull an item from the marketplace"); // Up for debate: Currently we don't allow items to be pulled if it's been bid on require(item.highestBidder == address(0), "Cannot pull from market once a bid has been placed"); require(block.timestamp >= item.listingCreationTime + 600, "Must wait ten minutes after listing before pulling from the market"); item.state = CANCELLED; IERC721(sombraNFTAddress).transferFrom( address(this), item.seller, item.tokenId ); itemsOnMarket[id] = item; emit ItemPulledFromMarket(id); } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; }
Up for debate: Currently we don't allow items to be pulled if it's been bid on
function pullFromMarket(uint256 id) external { require(id < itemsOnMarket.length, "Invalid id"); MarketItem memory item = itemsOnMarket[id]; require(item.state == ON_MARKET, "Item not for sale"); require(msg.sender == item.seller, "Only the item seller can pull an item from the marketplace"); require(item.highestBidder == address(0), "Cannot pull from market once a bid has been placed"); require(block.timestamp >= item.listingCreationTime + 600, "Must wait ten minutes after listing before pulling from the market"); item.state = CANCELLED; IERC721(sombraNFTAddress).transferFrom( address(this), item.seller, item.tokenId ); itemsOnMarket[id] = item; emit ItemPulledFromMarket(id); }
1,065,463
pragma solidity 0.5.4; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } contract CertificateControllerMock { // Address used by off-chain controller service to sign certificate mapping(address => bool) internal _certificateSigners; // A nonce used to ensure a certificate can be used only once mapping(address => uint256) internal _checkCount; event Checked(address sender); constructor(address _certificateSigner) public { _setCertificateSigner(_certificateSigner, true); } /** * @dev Modifier to protect methods with certificate control */ modifier isValidCertificate(bytes memory data) { require(_certificateSigners[msg.sender] || _checkCertificate(data, 0, 0x00000000), "A3: Transfer Blocked - Sender lockup period not ended"); _checkCount[msg.sender] += 1; // Increment sender check count emit Checked(msg.sender); _; } /** * @dev Get number of transations already sent to this contract by the sender * @param sender Address whom to check the counter of. * @return uint256 Number of transaction already sent to this contract. */ function checkCount(address sender) external view returns (uint256) { return _checkCount[sender]; } /** * @dev Get certificate signer authorization for an operator. * @param operator Address whom to check the certificate signer authorization for. * @return bool 'true' if operator is authorized as certificate signer, 'false' if not. */ function certificateSigners(address operator) external view returns (bool) { return _certificateSigners[operator]; } /** * @dev Set signer authorization for operator. * @param operator Address to add/remove as a certificate signer. * @param authorized 'true' if operator shall be accepted as certificate signer, 'false' if not. */ function _setCertificateSigner(address operator, bool authorized) internal { require(operator != address(0), "Action Blocked - Not a valid address"); _certificateSigners[operator] = authorized; } /** * @dev Checks if a certificate is correct * @param data Certificate to control */ function _checkCertificate(bytes memory data, uint256 /*value*/, bytes4 /*functionID*/) internal pure returns(bool) { // Comments to avoid compilation warnings for unused variables. if(data.length > 0 && (data[0] == hex"10" || data[0] == hex"11" || data[0] == hex"22")) { return true; } else { return false; } } } contract CertificateController is CertificateControllerMock { constructor(address _certificateSigner) public CertificateControllerMock(_certificateSigner) {} } /** * @title IERC777TokensRecipient * @dev ERC777TokensRecipient interface */ interface IERC777TokensRecipient { function canReceive( bytes32 partition, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external view returns(bool); function tokensReceived( bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external; } /** * @title IERC777TokensSender * @dev ERC777TokensSender interface */ interface IERC777TokensSender { function canTransfer( bytes32 partition, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external view returns(bool); function tokensToTransfer( bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external; } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ contract IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title IERC1410 partially fungible token standard * @dev ERC1410 interface */ interface IERC1410 { // Token Information function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256); // 1/10 function partitionsOf(address tokenHolder) external view returns (bytes32[] memory); // 2/10 // Token Transfers function transferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external returns (bytes32); // 3/10 function operatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external returns (bytes32); // 4/10 // Default Partition Management function getDefaultPartitions(address tokenHolder) external view returns (bytes32[] memory); // 5/10 function setDefaultPartitions(bytes32[] calldata partitions) external; // 6/10 // Operators function controllersByPartition(bytes32 partition) external view returns (address[] memory); // 7/10 function authorizeOperatorByPartition(bytes32 partition, address operator) external; // 8/10 function revokeOperatorByPartition(bytes32 partition, address operator) external; // 9/10 function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool); // 10/10 // Transfer Events event TransferByPartition( bytes32 indexed fromPartition, address operator, address indexed from, address indexed to, uint256 value, bytes data, bytes operatorData ); event ChangedPartition( bytes32 indexed fromPartition, bytes32 indexed toPartition, uint256 value ); // Operator Events event AuthorizedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder); event RevokedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder); } /** * @title IERC777 token standard * @dev ERC777 interface */ interface IERC777 { function name() external view returns (string memory); // 1/13 function symbol() external view returns (string memory); // 2/13 function totalSupply() external view returns (uint256); // 3/13 function balanceOf(address owner) external view returns (uint256); // 4/13 function granularity() external view returns (uint256); // 5/13 function controllers() external view returns (address[] memory); // 6/13 function authorizeOperator(address operator) external; // 7/13 function revokeOperator(address operator) external; // 8/13 function isOperatorFor(address operator, address tokenHolder) external view returns (bool); // 9/13 function transferWithData(address to, uint256 value, bytes calldata data) external; // 10/13 function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external; // 11/13 function redeem(uint256 value, bytes calldata data) external; // 12/13 function redeemFrom(address from, uint256 value, bytes calldata data, bytes calldata operatorData) external; // 13/13 event TransferWithData( address indexed operator, address indexed from, address indexed to, uint256 value, bytes data, bytes operatorData ); event Issued(address indexed operator, address indexed to, uint256 value, bytes data, bytes operatorData); event Redeemed(address indexed operator, address indexed from, uint256 value, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @title ERC1400 security token standard * @dev ERC1400 logic */ interface IERC1400 { // Document Management function getDocument(bytes32 name) external view returns (string memory, bytes32); // 1/9 function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external; // 2/9 event Document(bytes32 indexed name, string uri, bytes32 documentHash); // Controller Operation function isControllable() external view returns (bool); // 3/9 // Token Issuance function isIssuable() external view returns (bool); // 4/9 function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external; // 5/9 event IssuedByPartition(bytes32 indexed partition, address indexed operator, address indexed to, uint256 value, bytes data, bytes operatorData); // Token Redemption function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external; // 6/9 function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data, bytes calldata operatorData) external; // 7/9 event RedeemedByPartition(bytes32 indexed partition, address indexed operator, address indexed from, uint256 value, bytes data, bytes operatorData); // Transfer Validity function canTransferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32); // 8/9 function canOperatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external view returns (byte, bytes32, bytes32); // 9/9 } /** * Reason codes - ERC1066 * * To improve the token holder experience, canTransfer MUST return a reason byte code * on success or failure based on the EIP-1066 application-specific status codes specified below. * An implementation can also return arbitrary data as a bytes32 to provide additional * information not captured by the reason code. * * Code Reason * 0xA0 Transfer Verified - Unrestricted * 0xA1 Transfer Verified - On-Chain approval for restricted token * 0xA2 Transfer Verified - Off-Chain approval for restricted token * 0xA3 Transfer Blocked - Sender lockup period not ended * 0xA4 Transfer Blocked - Sender balance insufficient * 0xA5 Transfer Blocked - Sender not eligible * 0xA6 Transfer Blocked - Receiver not eligible * 0xA7 Transfer Blocked - Identity restriction * 0xA8 Transfer Blocked - Token restriction * 0xA9 Transfer Blocked - Token granularity */ contract ERC820Registry { function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external; function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address); function setManager(address _addr, address _newManager) external; function getManager(address _addr) public view returns(address); } /// Base client to interact with the registry. contract ERC820Client { ERC820Registry constant ERC820REGISTRY = ERC820Registry(0x820b586C8C28125366C998641B09DCbE7d4cBF06); function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); ERC820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation); } function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); return ERC820REGISTRY.getInterfaceImplementer(addr, interfaceHash); } function delegateManagement(address _newManager) internal { ERC820REGISTRY.setManager(address(this), _newManager); } } /** * @title ERC777 * @dev ERC777 logic */ contract ERC777 is IERC777, Ownable, ERC820Client, CertificateController, ReentrancyGuard { using SafeMath for uint256; string internal _name; string internal _symbol; uint256 internal _granularity; uint256 internal _totalSupply; // Indicate whether the token can still be controlled by operators or not anymore. bool internal _isControllable; // Mapping from tokenHolder to balance. mapping(address => uint256) internal _balances; /******************** Mappings related to operator **************************/ // Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC] mapping(address => mapping(address => bool)) internal _authorizedOperator; // Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] address[] internal _controllers; // Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] mapping(address => bool) internal _isController; /****************************************************************************/ /** * [ERC777 CONSTRUCTOR] * @dev Initialize ERC777 and CertificateController parameters + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner ) public CertificateController(certificateSigner) { _name = name; _symbol = symbol; _totalSupply = 0; require(granularity >= 1, "Constructor Blocked - Token granularity can not be lower than 1"); _granularity = granularity; _setControllers(controllers); setInterfaceImplementation("ERC777Token", address(this)); } /********************** ERC777 EXTERNAL FUNCTIONS ***************************/ /** * [ERC777 INTERFACE (1/13)] * @dev Get the name of the token, e.g., "MyToken". * @return Name of the token. */ function name() external view returns(string memory) { return _name; } /** * [ERC777 INTERFACE (2/13)] * @dev Get the symbol of the token, e.g., "MYT". * @return Symbol of the token. */ function symbol() external view returns(string memory) { return _symbol; } /** * [ERC777 INTERFACE (3/13)] * @dev Get the total number of issued tokens. * @return Total supply of tokens currently in circulation. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * [ERC777 INTERFACE (4/13)] * @dev Get the balance of the account with address 'tokenHolder'. * @param tokenHolder Address for which the balance is returned. * @return Amount of token held by 'tokenHolder' in the token contract. */ function balanceOf(address tokenHolder) external view returns (uint256) { return _balances[tokenHolder]; } /** * [ERC777 INTERFACE (5/13)] * @dev Get the smallest part of the token that’s not divisible. * @return The smallest non-divisible part of the token. */ function granularity() external view returns(uint256) { return _granularity; } /** * [ERC777 INTERFACE (6/13)] * @dev Get the list of controllers as defined by the token contract. * @return List of addresses of all the controllers. */ function controllers() external view returns (address[] memory) { return _controllers; } /** * [ERC777 INTERFACE (7/13)] * @dev Set a third party operator address as an operator of 'msg.sender' to transfer * and redeem tokens on its behalf. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperator(address operator) external { _authorizedOperator[operator][msg.sender] = true; emit AuthorizedOperator(operator, msg.sender); } /** * [ERC777 INTERFACE (8/13)] * @dev Remove the right of the operator address to be an operator for 'msg.sender' * and to transfer and redeem tokens on its behalf. * @param operator Address to rescind as an operator for 'msg.sender'. */ function revokeOperator(address operator) external { _authorizedOperator[operator][msg.sender] = false; emit RevokedOperator(operator, msg.sender); } /** * [ERC777 INTERFACE (9/13)] * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of tokenHolder. * @param tokenHolder Address of a token holder which may have the operator address as an operator. * @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool) { return _isOperatorFor(operator, tokenHolder); } /** * [ERC777 INTERFACE (10/13)] * @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferWithData(address to, uint256 value, bytes calldata data) external isValidCertificate(data) { _transferWithData("", msg.sender, msg.sender, to, value, data, "", true); } /** * [ERC777 INTERFACE (11/13)] * @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'. * @param from Token holder (or 'address(0)' to set from to 'msg.sender'). * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from'). * @param operatorData Information attached to the transfer by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _transferWithData("", msg.sender, _from, to, value, data, operatorData, true); } /** * [ERC777 INTERFACE (12/13)] * @dev Redeem the amount of tokens from the address 'msg.sender'. * @param value Number of tokens to redeem. * @param data Information attached to the redemption, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeem(uint256 value, bytes calldata data) external isValidCertificate(data) { _redeem("", msg.sender, msg.sender, value, data, ""); } /** * [ERC777 INTERFACE (13/13)] * @dev Redeem the amount of tokens on behalf of the address from. * @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender). * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeemFrom(address from, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _redeem("", msg.sender, _from, value, data, operatorData); } /********************** ERC777 INTERNAL FUNCTIONS ***************************/ /** * [INTERNAL] * @dev Check if 'value' is multiple of the granularity. * @param value The quantity that want's to be checked. * @return 'true' if 'value' is a multiple of the granularity. */ function _isMultiple(uint256 value) internal view returns(bool) { return(value.div(_granularity).mul(_granularity) == value); } /** * [INTERNAL] * @dev Check whether an address is a regular address or not. * @param addr Address of the contract that has to be checked. * @return 'true' if 'addr' is a regular address (not a contract). */ function _isRegularAddress(address addr) internal view returns(bool) { if (addr == address(0)) { return false; } uint size; assembly { size := extcodesize(addr) } // solhint-disable-line no-inline-assembly return size == 0; } /** * [INTERNAL] * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of 'tokenHolder'. * @param tokenHolder Address of a token holder which may have the 'operator' address as an operator. * @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise. */ function _isOperatorFor(address operator, address tokenHolder) internal view returns (bool) { return (operator == tokenHolder || _authorizedOperator[operator][tokenHolder] || (_isControllable && _isController[operator]) ); } /** * [INTERNAL] * @dev Perform the transfer of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. * @param operatorData Information attached to the transfer by the operator (if any).. * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'erc777tokenHolder'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _transferWithData( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(to != address(0), "A6: Transfer Blocked - Receiver not eligible"); require(_balances[from] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _callSender(partition, operator, from, to, value, data, operatorData); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _callRecipient(partition, operator, from, to, value, data, operatorData, preventLocking); emit TransferWithData(operator, from, to, value, data, operatorData); } /** * [INTERNAL] * @dev Perform the token redemption. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeem(bytes32 partition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(from != address(0), "A5: Transfer Blocked - Sender not eligible"); require(_balances[from] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _callSender(partition, operator, from, address(0), value, data, operatorData); _balances[from] = _balances[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Redeemed(operator, from, value, data, operatorData); } /** * [INTERNAL] * @dev Check for 'ERC777TokensSender' hook on the sender and call it. * May throw according to 'preventLocking'. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the balance decrease (through transfer or redemption). * @param from Token holder. * @param to Token recipient for a transfer and 0x for a redemption. * @param value Number of tokens the token holder balance is decreased by. * @param data Extra information. * @param operatorData Extra information, attached by the operator (if any). */ function _callSender( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(from, "ERC777TokensSender"); if (senderImplementation != address(0)) { IERC777TokensSender(senderImplementation).tokensToTransfer(partition, operator, from, to, value, data, operatorData); } } /** * [INTERNAL] * @dev Check for 'ERC777TokensRecipient' hook on the recipient and call it. * May throw according to 'preventLocking'. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the balance increase (through transfer or issuance). * @param from Token holder for a transfer and 0x for an issuance. * @param to Token recipient. * @param value Number of tokens the recipient balance is increased by. * @param data Extra information, intended for the token holder ('from'). * @param operatorData Extra information attached by the operator (if any). * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'ERC777TokensRecipient'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _callRecipient( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal { address recipientImplementation; recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient"); if (recipientImplementation != address(0)) { IERC777TokensRecipient(recipientImplementation).tokensReceived(partition, operator, from, to, value, data, operatorData); } else if (preventLocking) { require(_isRegularAddress(to), "A6: Transfer Blocked - Receiver not eligible"); } } /** * [INTERNAL] * @dev Perform the issuance of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance, and intended for the recipient (to). * @param operatorData Information attached to the issuance by the operator (if any). */ function _issue(bytes32 partition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(to != address(0), "A6: Transfer Blocked - Receiver not eligible"); _totalSupply = _totalSupply.add(value); _balances[to] = _balances[to].add(value); _callRecipient(partition, operator, address(0), to, value, data, operatorData, true); emit Issued(operator, to, value, data, operatorData); } /********************** ERC777 OPTIONAL FUNCTIONS ***************************/ /** * [NOT MANDATORY FOR ERC777 STANDARD] * @dev Set list of token controllers. * @param operators Controller addresses. */ function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } } /** * @title ERC1410 * @dev ERC1410 logic */ contract ERC1410 is IERC1410, ERC777{ /******************** Mappings to find partition ******************************/ // List of partitions. bytes32[] internal _totalPartitions; // Mapping from partition to global balance of corresponding partition. mapping (bytes32 => uint256) internal _totalSupplyByPartition; // Mapping from tokenHolder to their partitions. mapping (address => bytes32[]) internal _partitionsOf; // Mapping from (tokenHolder, partition) to balance of corresponding partition. mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition; // Mapping from tokenHolder to their default partitions (for ERC777 and ERC20 compatibility). mapping (address => bytes32[]) internal _defaultPartitionsOf; // List of token default partitions (for ERC20 compatibility). bytes32[] internal _tokenDefaultPartitions; /****************************************************************************/ /**************** Mappings to find partition operators ************************/ // Mapping from (tokenHolder, partition, operator) to 'approved for partition' status. [TOKEN-HOLDER-SPECIFIC] mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition; // Mapping from partition to controllers for the partition. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => address[]) internal _controllersByPartition; // Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition; /****************************************************************************/ /** * [ERC1410 CONSTRUCTOR] * @dev Initialize ERC1410 parameters + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions ) public ERC777(name, symbol, granularity, controllers, certificateSigner) { _tokenDefaultPartitions = tokenDefaultPartitions; } /********************** ERC1410 EXTERNAL FUNCTIONS **************************/ /** * [ERC1410 INTERFACE (1/10)] * @dev Get balance of a tokenholder for a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which the balance is returned. * @return Amount of token of partition 'partition' held by 'tokenHolder' in the token contract. */ function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256) { return _balanceOfByPartition[tokenHolder][partition]; } /** * [ERC1410 INTERFACE (2/10)] * @dev Get partitions index of a tokenholder. * @param tokenHolder Address for which the partitions index are returned. * @return Array of partitions index of 'tokenHolder'. */ function partitionsOf(address tokenHolder) external view returns (bytes32[] memory) { return _partitionsOf[tokenHolder]; } /** * [ERC1410 INTERFACE (3/10)] * @dev Transfer tokens from a specific partition. * @param partition Name of the partition. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return Destination partition. */ function transferByPartition( bytes32 partition, address to, uint256 value, bytes calldata data ) external isValidCertificate(data) returns (bytes32) { return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, ""); } /** * [ERC1410 INTERFACE (4/10)] * @dev Transfer tokens from a specific partition through an operator. * @param partition Name of the partition. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return Destination partition. */ function operatorTransferByPartition( bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external isValidCertificate(operatorData) returns (bytes32) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorForPartition(partition, msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); return _transferByPartition(partition, msg.sender, _from, to, value, data, operatorData); } /** * [ERC1410 INTERFACE (5/10)] * @dev Get default partitions to transfer from. * Function used for ERC777 and ERC20 backwards compatibility. * For example, a security token may return the bytes32("unrestricted"). * @param tokenHolder Address for which we want to know the default partitions. * @return Array of default partitions. */ function getDefaultPartitions(address tokenHolder) external view returns (bytes32[] memory) { return _defaultPartitionsOf[tokenHolder]; } /** * [ERC1410 INTERFACE (6/10)] * @dev Set default partitions to transfer from. * Function used for ERC777 and ERC20 backwards compatibility. * @param partitions partitions to use by default when not specified. */ function setDefaultPartitions(bytes32[] calldata partitions) external { _defaultPartitionsOf[msg.sender] = partitions; } /** * [ERC1410 INTERFACE (7/10)] * @dev Get controllers for a given partition. * Function used for ERC777 and ERC20 backwards compatibility. * @param partition Name of the partition. * @return Array of controllers for partition. */ function controllersByPartition(bytes32 partition) external view returns (address[] memory) { return _controllersByPartition[partition]; } /** * [ERC1410 INTERFACE (8/10)] * @dev Set 'operator' as an operator for 'msg.sender' for a given partition. * @param partition Name of the partition. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperatorByPartition(bytes32 partition, address operator) external { _authorizedOperatorByPartition[msg.sender][partition][operator] = true; emit AuthorizedOperatorByPartition(partition, operator, msg.sender); } /** * [ERC1410 INTERFACE (9/10)] * @dev Remove the right of the operator address to be an operator on a given * partition for 'msg.sender' and to transfer and redeem tokens on its behalf. * @param partition Name of the partition. * @param operator Address to rescind as an operator on given partition for 'msg.sender'. */ function revokeOperatorByPartition(bytes32 partition, address operator) external { _authorizedOperatorByPartition[msg.sender][partition][operator] = false; emit RevokedOperatorByPartition(partition, operator, msg.sender); } /** * [ERC1410 INTERFACE (10/10)] * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool) { return _isOperatorForPartition(partition, operator, tokenHolder); } /********************** ERC1410 INTERNAL FUNCTIONS **************************/ /** * [INTERNAL] * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) { return (_isOperatorFor(operator, tokenHolder) || _authorizedOperatorByPartition[tokenHolder][partition][operator] || (_isControllable && _isControllerByPartition[partition][operator]) ); } /** * [INTERNAL] * @dev Transfer tokens from a specific partition. * @param fromPartition Partition of the tokens to transfer. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator (if any). * @return Destination partition. */ function _transferByPartition( bytes32 fromPartition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal returns (bytes32) { require(_balanceOfByPartition[from][fromPartition] >= value, "A4: Transfer Blocked - Sender balance insufficient"); // ensure enough funds bytes32 toPartition = fromPartition; if(operatorData.length != 0 && data.length != 0) { toPartition = _getDestinationPartition(fromPartition, data); } _removeTokenFromPartition(from, fromPartition, value); _transferWithData(fromPartition, operator, from, to, value, data, operatorData, true); _addTokenToPartition(to, toPartition, value); emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData); if(toPartition != fromPartition) { emit ChangedPartition(fromPartition, toPartition, value); } return toPartition; } /** * [INTERNAL] * @dev Remove a token from a specific partition. * @param from Token holder. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal { _balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value); _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value); // If the balance of the TokenHolder's partition is zero, finds and deletes the partition. if(_balanceOfByPartition[from][partition] == 0) { for (uint i = 0; i < _partitionsOf[from].length; i++) { if(_partitionsOf[from][i] == partition) { _partitionsOf[from][i] = _partitionsOf[from][_partitionsOf[from].length - 1]; delete _partitionsOf[from][_partitionsOf[from].length - 1]; _partitionsOf[from].length--; break; } } } // If the total supply is zero, finds and deletes the partition. if(_totalSupplyByPartition[partition] == 0) { for (uint i = 0; i < _totalPartitions.length; i++) { if(_totalPartitions[i] == partition) { _totalPartitions[i] = _totalPartitions[_totalPartitions.length - 1]; delete _totalPartitions[_totalPartitions.length - 1]; _totalPartitions.length--; break; } } } } /** * [INTERNAL] * @dev Add a token to a specific partition. * @param to Token recipient. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal { if(value != 0) { if(_balanceOfByPartition[to][partition] == 0) { _partitionsOf[to].push(partition); } _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value); if(_totalSupplyByPartition[partition] == 0) { _totalPartitions.push(partition); } _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value); } } /** * [INTERNAL] * @dev Retrieve the destination partition from the 'data' field. * By convention, a partition change is requested ONLY when 'data' starts * with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff * When the flag is detected, the destination tranche is extracted from the * 32 bytes following the flag. * @param fromPartition Partition of the tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @return Destination partition. */ function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) { bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 flag; assembly { flag := mload(add(data, 32)) } if(flag == changePartitionFlag) { assembly { toPartition := mload(add(data, 64)) } } else { toPartition = fromPartition; } } /** * [INTERNAL] * @dev Get the sender's default partition if setup, or the global default partition if not. * @param tokenHolder Address for which the default partition is returned. * @return Default partition. */ function _getDefaultPartitions(address tokenHolder) internal view returns(bytes32[] memory) { if(_defaultPartitionsOf[tokenHolder].length != 0) { return _defaultPartitionsOf[tokenHolder]; } else { return _tokenDefaultPartitions; } } /********************* ERC1410 OPTIONAL FUNCTIONS ***************************/ /** * [NOT MANDATORY FOR ERC1410 STANDARD] * @dev Get list of existing partitions. * @return Array of all exisiting partitions. */ function totalPartitions() external view returns (bytes32[] memory) { return _totalPartitions; } /** * [NOT MANDATORY FOR ERC1410 STANDARD][SHALL BE CALLED ONLY FROM ERC1400] * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */ function _setPartitionControllers(bytes32 partition, address[] memory operators) internal { for (uint i = 0; i<_controllersByPartition[partition].length; i++){ _isControllerByPartition[partition][_controllersByPartition[partition][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isControllerByPartition[partition][operators[j]] = true; } _controllersByPartition[partition] = operators; } /************** ERC777 BACKWARDS RETROCOMPATIBILITY *************************/ /** * [NOT MANDATORY FOR ERC1410 STANDARD][OVERRIDES ERC777 METHOD] * @dev Transfer the value of tokens from the address 'msg.sender' to the address 'to'. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferWithData(address to, uint256 value, bytes calldata data) external isValidCertificate(data) { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, data, ""); } /** * [NOT MANDATORY FOR ERC1410 STANDARD][OVERRIDES ERC777 METHOD] * @dev Transfer the value of tokens on behalf of the address from to the address to. * @param from Token holder (or 'address(0)'' to set from to 'msg.sender'). * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from'). [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _transferByDefaultPartitions(msg.sender, _from, to, value, data, operatorData); } /** * [NOT MANDATORY FOR ERC1410 STANDARD][OVERRIDES ERC777 METHOD] * @dev Empty function to erase ERC777 redeem() function since it doesn't handle partitions. */ function redeem(uint256 /*value*/, bytes calldata /*data*/) external { // Comments to avoid compilation warnings for unused variables. } /** * [NOT MANDATORY FOR ERC1410 STANDARD][OVERRIDES ERC777 METHOD] * @dev Empty function to erase ERC777 redeemFrom() function since it doesn't handle partitions. */ function redeemFrom(address /*from*/, uint256 /*value*/, bytes calldata /*data*/, bytes calldata /*operatorData*/) external { // Comments to avoid compilation warnings for unused variables. } /** * [NOT MANDATORY FOR ERC1410 STANDARD] * @dev Transfer tokens from default partitions. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION]. * @param operatorData Information attached to the transfer by the operator (if any). */ function _transferByDefaultPartitions( address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { bytes32[] memory _partitions = _getDefaultPartitions(from); require(_partitions.length != 0, "A8: Transfer Blocked - Token restriction"); uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _partitions.length; i++) { _localBalance = _balanceOfByPartition[from][_partitions[i]]; if(_remainingValue <= _localBalance) { _transferByPartition(_partitions[i], operator, from, to, _remainingValue, data, operatorData); _remainingValue = 0; break; } else { _transferByPartition(_partitions[i], operator, from, to, _localBalance, data, operatorData); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "A8: Transfer Blocked - Token restriction"); } } /** * @title ERC1400 * @dev ERC1400 logic */ contract ERC1400 is IERC1400, ERC1410, MinterRole { struct Doc { string docURI; bytes32 docHash; } // Mapping for token URIs. mapping(bytes32 => Doc) internal _documents; // Indicate whether the token can still be issued by the issuer or not anymore. bool internal _isIssuable; /** * @dev Modifier to verify if token is issuable. */ modifier issuableToken() { require(_isIssuable, "A8, Transfer Blocked - Token restriction"); _; } /** * [ERC1400 CONSTRUCTOR] * @dev Initialize ERC1400 + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions ) public ERC1410(name, symbol, granularity, controllers, certificateSigner, tokenDefaultPartitions) { setInterfaceImplementation("ERC1400Token", address(this)); _isControllable = true; _isIssuable = true; } /********************** ERC1400 EXTERNAL FUNCTIONS **************************/ /** * [ERC1400 INTERFACE (1/9)] * @dev Access a document associated with the token. * @param name Short name (represented as a bytes32) associated to the document. * @return Requested document + document hash. */ function getDocument(bytes32 name) external view returns (string memory, bytes32) { require(bytes(_documents[name].docURI).length != 0, "Action Blocked - Empty document"); return ( _documents[name].docURI, _documents[name].docHash ); } /** * [ERC1400 INTERFACE (2/9)] * @dev Associate a document with the token. * @param name Short name (represented as a bytes32) associated to the document. * @param uri Document content. * @param documentHash Hash of the document [optional parameter]. */ function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external onlyOwner { _documents[name] = Doc({ docURI: uri, docHash: documentHash }); emit Document(name, uri, documentHash); } /** * [ERC1400 INTERFACE (3/9)] * @dev Know if the token can be controlled by operators. * If a token returns 'false' for 'isControllable()'' then it MUST always return 'false' in the future. * @return bool 'true' if the token can still be controlled by operators, 'false' if it can't anymore. */ function isControllable() external view returns (bool) { return _isControllable; } /** * [ERC1400 INTERFACE (4/9)] * @dev Know if new tokens can be issued in the future. * @return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore. */ function isIssuable() external view returns (bool) { return _isIssuable; } /** * [ERC1400 INTERFACE (5/9)] * @dev Issue tokens from a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to issue tokens. * @param value Number of tokens issued. * @param data Information attached to the issuance, by the issuer. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external onlyMinter issuableToken isValidCertificate(data) { _issueByPartition(partition, msg.sender, tokenHolder, value, data, ""); } /** * [ERC1400 INTERFACE (6/9)] * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param value Number of tokens redeemed. * @param data Information attached to the redemption, by the redeemer. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external isValidCertificate(data) { _redeemByPartition(partition, msg.sender, msg.sender, value, data, ""); } /** * [ERC1400 INTERFACE (7/9)] * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to redeem tokens. * @param value Number of tokens redeemed. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (tokenHolder == address(0)) ? msg.sender : tokenHolder; require(_isOperatorForPartition(partition, msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _redeemByPartition(partition, msg.sender, _from, value, data, operatorData); } /** * [ERC1400 INTERFACE (8/9)] * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param partition Name of the partition. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function canTransferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32) { if(!_checkCertificate(data, 0, 0xf3d490db)) { // 4 first bytes of keccak256(transferByPartition(bytes32,address,uint256,bytes)) return(hex"A3", "", partition); // Transfer Blocked - Sender lockup period not ended } else { return _canTransfer(partition, msg.sender, msg.sender, to, value, data, ""); } } /** * [ERC1400 INTERFACE (9/9)] * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param partition Name of the partition. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function canOperatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external view returns (byte, bytes32, bytes32) { if(!_checkCertificate(operatorData, 0, 0x8c0dee9c)) { // 4 first bytes of keccak256(operatorTransferByPartition(bytes32,address,address,uint256,bytes,bytes)) return(hex"A3", "", partition); // Transfer Blocked - Sender lockup period not ended } else { address _from = (from == address(0)) ? msg.sender : from; return _canTransfer(partition, msg.sender, _from, to, value, data, operatorData); } } /********************** ERC1400 INTERNAL FUNCTIONS **************************/ /** * [INTERNAL] * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param partition Name of the partition. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator (if any). * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function _canTransfer(bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData) internal view returns (byte, bytes32, bytes32) { if(!_isOperatorForPartition(partition, operator, from)) return(hex"A7", "", partition); // "Transfer Blocked - Identity restriction" if((_balances[from] < value) || (_balanceOfByPartition[from][partition] < value)) return(hex"A4", "", partition); // Transfer Blocked - Sender balance insufficient if(to == address(0)) return(hex"A6", "", partition); // Transfer Blocked - Receiver not eligible address senderImplementation; address recipientImplementation; senderImplementation = interfaceAddr(from, "ERC777TokensSender"); recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient"); if((senderImplementation != address(0)) && !IERC777TokensSender(senderImplementation).canTransfer(partition, from, to, value, data, operatorData)) return(hex"A5", "", partition); // Transfer Blocked - Sender not eligible if((recipientImplementation != address(0)) && !IERC777TokensRecipient(recipientImplementation).canReceive(partition, from, to, value, data, operatorData)) return(hex"A6", "", partition); // Transfer Blocked - Receiver not eligible if(!_isMultiple(value)) return(hex"A9", "", partition); // Transfer Blocked - Token granularity return(hex"A2", "", partition); // Transfer Verified - Off-Chain approval for restricted token } /** * [INTERNAL] * @dev Issue tokens from a specific partition. * @param toPartition Name of the partition. * @param operator The address performing the issuance. * @param to Token recipient. * @param value Number of tokens to issue. * @param data Information attached to the issuance. * @param operatorData Information attached to the issuance, by the operator (if any). */ function _issueByPartition( bytes32 toPartition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { _issue(toPartition, operator, to, value, data, operatorData); _addTokenToPartition(to, toPartition, value); emit IssuedByPartition(toPartition, operator, to, value, data, operatorData); } /** * [INTERNAL] * @dev Redeem tokens of a specific partition. * @param fromPartition Name of the partition. * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeemByPartition( bytes32 fromPartition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal { require(_balanceOfByPartition[from][fromPartition] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _removeTokenFromPartition(from, fromPartition, value); _redeem(fromPartition, operator, from, value, data, operatorData); emit RedeemedByPartition(fromPartition, operator, from, value, data, operatorData); } /********************** ERC1400 OPTIONAL FUNCTIONS **************************/ /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Definitely renounce the possibility to control tokens on behalf of tokenHolders. * Once set to false, '_isControllable' can never be set to 'true' again. */ function renounceControl() external onlyOwner { _isControllable = false; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Definitely renounce the possibility to issue new tokens. * Once set to false, '_isIssuable' can never be set to 'true' again. */ function renounceIssuance() external onlyOwner { _isIssuable = false; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Set list of token controllers. * @param operators Controller addresses. */ function setControllers(address[] calldata operators) external onlyOwner { _setControllers(operators); } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */ function setPartitionControllers(bytes32 partition, address[] calldata operators) external onlyOwner { _setPartitionControllers(partition, operators); } /** * @dev Add a certificate signer for the token. * @param operator Address to set as a certificate signer. * @param authorized 'true' if operator shall be accepted as certificate signer, 'false' if not. */ function setCertificateSigner(address operator, bool authorized) external onlyOwner { _setCertificateSigner(operator, authorized); } /************* ERC1410/ERC777 BACKWARDS RETROCOMPATIBILITY ******************/ /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Get token default partitions to send from. * Function used for ERC777 and ERC20 backwards compatibility. * For example, a security token may return the bytes32("unrestricted"). * @return Default partitions. */ function getTokenDefaultPartitions() external view returns (bytes32[] memory) { return _tokenDefaultPartitions; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Set token default partitions to send from. * Function used for ERC777 and ERC20 backwards compatibility. * @param defaultPartitions Partitions to use by default when not specified. */ function setTokenDefaultPartitions(bytes32[] calldata defaultPartitions) external onlyOwner { _tokenDefaultPartitions = defaultPartitions; } /** * [NOT MANDATORY FOR ERC1400 STANDARD][OVERRIDES ERC1410 METHOD] * @dev Redeem the value of tokens from the address 'msg.sender'. * @param value Number of tokens to redeem. * @param data Information attached to the redemption, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeem(uint256 value, bytes calldata data) external isValidCertificate(data) { _redeemByDefaultPartitions(msg.sender, msg.sender, value, data, ""); } /** * [NOT MANDATORY FOR ERC1400 STANDARD][OVERRIDES ERC1410 METHOD] * @dev Redeem the value of tokens on behalf of the address 'from'. * @param from Token holder whose tokens will be redeemed (or 'address(0)' to set from to 'msg.sender'). * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeemFrom(address from, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _redeemByDefaultPartitions(msg.sender, _from, value, data, operatorData); } /** * [NOT MANDATORY FOR ERC1410 STANDARD] * @dev Redeem tokens from a default partitions. * @param operator The address performing the redeem. * @param from Token holder. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal { bytes32[] memory _partitions = _getDefaultPartitions(from); require(_partitions.length != 0, "A8: Transfer Blocked - Token restriction"); uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _partitions.length; i++) { _localBalance = _balanceOfByPartition[from][_partitions[i]]; if(_remainingValue <= _localBalance) { _redeemByPartition(_partitions[i], operator, from, _remainingValue, data, operatorData); _remainingValue = 0; break; } else { _redeemByPartition(_partitions[i], operator, from, _localBalance, data, operatorData); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "A8: Transfer Blocked - Token restriction"); } } /** * @title ERC1400ERC20 * @dev ERC1400 with ERC20 retrocompatibility */ contract ERC1400ERC20 is IERC20, ERC1400 { // Mapping from (tokenHolder, spender) to allowed value. mapping (address => mapping (address => uint256)) internal _allowed; // Mapping from (tokenHolder) to whitelisted status. mapping (address => bool) internal _whitelisted; /** * @dev Modifier to verify if sender and recipient are whitelisted. */ modifier isWhitelisted(address recipient) { require(_whitelisted[recipient], "A3: Transfer Blocked - Sender lockup period not ended"); _; } /** * [ERC1400ERC20 CONSTRUCTOR] * @dev Initialize ERC71400ERC20 and CertificateController parameters + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions ) public ERC1400(name, symbol, granularity, controllers, certificateSigner, tokenDefaultPartitions) { setInterfaceImplementation("ERC20Token", address(this)); } /** * [OVERRIDES ERC1400 METHOD] * @dev Perform the transfer of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. * @param operatorData Information attached to the transfer by the operator (if any). * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'erc777tokenHolder'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _transferWithData( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal { ERC777._transferWithData(partition, operator, from, to, value, data, operatorData, preventLocking); emit Transfer(from, to, value); } /** * [OVERRIDES ERC1400 METHOD] * @dev Perform the token redemption. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption by the operator (if any). */ function _redeem(bytes32 partition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData) internal { ERC777._redeem(partition, operator, from, value, data, operatorData); emit Transfer(from, address(0), value); // ERC20 backwards compatibility } /** * [OVERRIDES ERC1400 METHOD] * @dev Perform the issuance of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance. * @param operatorData Information attached to the issuance by the operator (if any). */ function _issue(bytes32 partition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData) internal { ERC777._issue(partition, operator, to, value, data, operatorData); emit Transfer(address(0), to, value); // ERC20 backwards compatibility } /** * [OVERRIDES ERC1400 METHOD] * @dev Get the number of decimals of the token. * @return The number of decimals of the token. For Backwards compatibility, decimals are forced to 18 in ERC777. */ function decimals() external pure returns(uint8) { return uint8(18); } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Check the value 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 value of tokens still available for the spender. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowed[owner][spender]; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @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. * @return A boolean that indicates if the operation was successful. */ function approve(address spender, uint256 value) external returns (bool) { require(spender != address(0), "A5: Transfer Blocked - Sender not eligible"); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Transfer token for a specified address. * @param to The address to transfer to. * @param value The value to be transferred. * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) external isWhitelisted(to) returns (bool) { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, "", ""); return true; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Transfer tokens from one address to another. * @param from The address which you want to transfer tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean that indicates if the operation was successful. */ function transferFrom(address from, address to, uint256 value) external isWhitelisted(to) returns (bool) { address _from = (from == address(0)) ? msg.sender : from; require( _isOperatorFor(msg.sender, _from) || (value <= _allowed[_from][msg.sender]), "A7: Transfer Blocked - Identity restriction"); if(_allowed[_from][msg.sender] >= value) { _allowed[_from][msg.sender] = _allowed[_from][msg.sender].sub(value); } else { _allowed[_from][msg.sender] = 0; } _transferByDefaultPartitions(msg.sender, _from, to, value, "", ""); return true; } /***************** ERC1400ERC20 OPTIONAL FUNCTIONS ***************************/ /** * [NOT MANDATORY FOR ERC1400ERC20 STANDARD] * @dev Get whitelisted status for a tokenHolder. * @param tokenHolder Address whom to check the whitelisted status for. * @return bool 'true' if tokenHolder is whitelisted, 'false' if not. */ function whitelisted(address tokenHolder) external view returns (bool) { return _whitelisted[tokenHolder]; } /** * [NOT MANDATORY FOR ERC1400ERC20 STANDARD] * @dev Set whitelisted status for a tokenHolder. * @param tokenHolder Address to add/remove from whitelist. * @param authorized 'true' if tokenHolder shall be added to whitelist, 'false' if not. */ function setWhitelisted(address tokenHolder, bool authorized) external onlyOwner { _setWhitelisted(tokenHolder, authorized); } /** * [NOT MANDATORY FOR ERC1400ERC20 STANDARD] * @dev Set whitelisted status for a tokenHolder. * @param tokenHolder Address to add/remove from whitelist. * @param authorized 'true' if tokenHolder shall be added to whitelist, 'false' if not. */ function _setWhitelisted(address tokenHolder, bool authorized) internal { require(tokenHolder != address(0), "Action Blocked - Not a valid address"); _whitelisted[tokenHolder] = authorized; } }
[NOT MANDATORY FOR ERC1410 STANDARD][OVERRIDES ERC777 METHOD] Transfer the value of tokens on behalf of the address from to the address to. from Token holder (or 'address(0)'' to set from to 'msg.sender'). to Token recipient. value Number of tokens to transfer. data Information attached to the transfer, and intended for the token holder ('from'). [CAN CONTAIN THE DESTINATION PARTITION] operatorData Information attached to the transfer by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE]/
function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _transferByDefaultPartitions(msg.sender, _from, to, value, data, operatorData); }
2,563,774
pragma solidity ^0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ struct Airline{ bytes name; bool isRegistered; bool canVote; } address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => Airline) private airlines; //Airlines are contract accounts, so we represent them as addresses. //Another approach can be to make a struct Airline. But let's keep it simple. uint256 private airlinesCount; //The number of registered airlines. mapping(address => bool) private authorizedCallers; //Used to keep track of which app contracts can access this contract uint M =2; //Voting threshold, starts when there are at least 4 registered airlines address[] private multiCallsOp = new address[](0); //List of voters on changing the operational mode /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirline ) public { contractOwner = msg.sender; airlines[firstAirline].isRegistered = true; //Project Specification: First airline is registered when contract is deployed. airlines[firstAirline].canVote = false; //First airline must provide funding before it can vote for others to join airlinesCount = 1; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the calling contract to be in the "authorizedCallers" list * This is used on all functions(except those who are called by the contract owner) * to ensure that only the authorized app contracts gain access to the data on this contract */ modifier requireAuthorizedCaller() { require(authorizedCallers[msg.sender], "Caller is not authorized"); _; // All modifiers require an "_" which indicates where the function body will be added } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Sets which app contracts can access this data contract * * This method is used to authorize a FlightSuretyApp contract to interact with FlightSuretyData. * You can use it to change which FlightSuretyApp is active. But it is not required */ function authorizeCaller ( address appContract ) external requireContractOwner requireIsOperational { authorizedCallers[appContract] = true; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view //requireAuthorizedCaller returns(bool) { return operational; } /** * @dev Checks if an airline can vote * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function canVote ( address airline ) external view //pure requireIsOperational //requireAuthorizedCaller returns(bool) { return (airlines[airline].canVote); } /** * @dev Does the voting work for multisignature functions * Keeps track of voting responses, * and returns true if the voting threshold is rechead so the caller function can perform the task */ function vote(address voter) private returns(bool success) { require(voter == contractOwner || airlines[voter].canVote, "This address cannot vote."); success = false; bool isDuplicate = false; for(uint c = 0; c < multiCallsOp.length; c++) { if(multiCallsOp[c] == voter) { isDuplicate = true; break; } } require(!isDuplicate, "Caller already voted on changing operational mode"); multiCallsOp.push(voter); uint votes = multiCallsOp.length; if(votes >= M) //Voting threshold reached -> Change operational mode { multiCallsOp = new address[](0); //Reset list of voters success = true; } return(success); } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external //requireContractOwner { require(mode != operational, "Operational status already set to given mode"); if(airlinesCount < 4) //Voting threshold not reached yet { require(msg.sender == contractOwner, "Message sender is not allowed to change the operational mode of the contract"); operational = mode; } else if(vote(msg.sender)) operational = mode; } /** * @dev Checks if an airline is already registered * Can only be called from FlightSuretyApp contract * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function isRegistered ( address airline ) external view //pure requireIsOperational //requireAuthorizedCaller returns(bool) { return (airlines[airline].isRegistered); } /** * @dev Returns the number of registered airlines * */ function RegisteredAirlinesCount ( ) external view //pure //requireIsOperational //OK to reveal the count even if contract is not operational //requireAuthorizedCaller returns(uint) { return (airlinesCount); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function registerAirline ( address airline ) external //view //pure requireIsOperational //requireAuthorizedCaller { //require(airlines[airline].isRegistered == false, "This airline is already registered"); //App contract already checks it. airlines[airline].isRegistered = true; airlines[airline].canVote = false; airlinesCount++; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function enableVoting ( ) external payable//view //pure requireIsOperational //requireAuthorizedCaller { require(airlines[msg.sender].canVote == false, "This airline already can vote"); require(airlines[msg.sender].isRegistered, "This airline is not registered"); require(msg.value >= 10 ether, "Not enough funds to enable voting for this airline"); airlines[msg.sender].canVote = true; require(airlines[msg.sender].canVote, "Failed to enable voting!"); } /** * @dev Buy insurance for a flight * */ struct insuredFlights{ //bytes32[] flightNames; //a list of insured flights for each customer //uint[] amounts; // holds insurance amounts for each insured flight in wei mapping(bytes32 => uint) insuranceDetails; //stores how much did the customer insure for each flight bytes32[] insuranceKeys; //used to search the above mapping--e.g. to view all insured flights } mapping(address => insuredFlights) allInsuredFlights; mapping(address => uint) payouts; //Amounts owed to insurees but have not yet been credited to their accounts //These will be credited to the insurees when they initiate a withdrawal. //event payout(uint amount, address insuree); //This contract is not directly connected to the frontend, no need for events here. function buy ( address customer, bytes32 flight, uint amount ) external //payable //The fees are kept in the app contract requireIsOperational //requireAuthorizedCaller { // 1. Check the customer did not insure this flight previously: require(allInsuredFlights[customer].insuranceDetails[flight] == 0, 'This flight is already insured by this customer'); // 2. Accept insurance: allInsuredFlights[customer].insuranceDetails[flight] = amount; allInsuredFlights[customer].insuranceKeys.push(flight); } /** * @dev Allow a user to view the list of flights they insured * */ function viewInsuredFlights ( address customer ) external returns(bytes32[] memory) { return( allInsuredFlights[customer].insuranceKeys); } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 flight, address insuree ) external requireIsOperational //Apply Re-entrancy Gaurd Here(not required by project) //requireAuthorizedCaller returns(uint credit) //This is a state-changing function, so it cannot return a value //We will inform caller of the credit amount by emitting an event { //1. Checks credit = allInsuredFlights[insuree].insuranceDetails[flight]; require(credit > 0, 'You either did not insure this flight from before, or you have already claimed the credit for this flight.'); //2. Effects //2.a Update the insurance information in your mapping allInsuredFlights[insuree].insuranceDetails[flight] = 0; //2.b Calculate the amount the customer must be refunded: 1.5 time the insurance amount credit = credit.mul(3); credit = credit.div(2); require(allInsuredFlights[insuree].insuranceDetails[flight] == 0, 'Could not payout your credit'); //3. Interaction payouts[insuree] = payouts[insuree].add(credit); require(payouts[insuree] > 0, 'Unable to add your credit to the payout system'); //web3.js is not connected to this contract, you need to emit from the app contract //just return the tuples and the app contract should do the emit back to the front end //emit payout(credit, insuree); //Next: when the emitted event is caught in the frontend, allow user to withdraw amount -> withdraw button should appear } function getCredit ( address insuree ) external view returns(uint credit) { credit = payouts[insuree]; return credit; } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address insuree ) public requireIsOperational //requireAuthorizedCaller { uint credit = payouts[insuree]; //1. Checks require(credit > 0, 'User does not have credit to withraw'); //2. Effects payouts[insuree] = 0; //reset credit to prevent multiple withrawal of the same credit require(payouts[insuree] == 0, 'Could not withdraw credit'); //3. Interaction insuree.transfer(credit); //insuree.call.value(credit)(""); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address insuree, bytes32 flight ) external payable requireIsOperational //requireAuthorizedCaller { // 1. Check the customer did not insure this flight previously: require(allInsuredFlights[insuree].insuranceDetails[flight] == 0, 'This flight is already insured by this customer'); // 2. Accept insurance: allInsuredFlights[insuree].insuranceDetails[flight] = msg.value; //allInsuredFlights[insuree].insuranceKeys.push(flight); //to be able to show the customer later all the flights he insured //feature not required and needs to be fixed later. } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable requireIsOperational //requireAuthorizedCaller { //fund(); } }
Fallback function for funding smart contract./requireAuthorizedCallerfund();
function() external payable requireIsOperational { }
14,078,390
./full_match/4/0xB34756f8D9682ab6C26F77f9461207a65c52c8bC/sources/contracts/IVaultHandler.sol
Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimum vault ratio _amount of tokens to burn _amount should be higher than 0 A fee of exactly burnFee must be sent as value on ETH The fee goes to the treasury contract if reward handler is set exit rewards/send back ETH above fee
function burn(uint256 _amount) external payable virtual nonReentrant vaultExists whenNotPaused notZero(_amount) { uint256 fee = getFee(_amount); require( msg.value >= fee, "VaultHandler::burn: burn fee less than required" ); Vault memory vault = vaults[userToVault[msg.sender]]; _burn(vault.Id, _amount); safeTransferETH(treasury, fee); safeTransferETH(msg.sender, msg.value.sub(fee)); emit TokensBurned(msg.sender, vault.Id, _amount); }
12,419,680
/** t.me/apenote Jeets will be punished. */ pragma solidity ^0.8.10; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } 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); } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } contract ApeNote is Context, IERC20, Ownable { //// mapping (address => uint) private _owned; mapping (address => mapping (address => uint)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => User) private cooldown; mapping (address => bool) private _isBot; uint private constant _totalSupply = 1e17 * 10**9; string public constant name = unicode"ApeNote"; //// string public constant symbol = unicode"ANOTE"; //// uint8 public constant decimals = 9; IUniswapV2Router02 private uniswapV2Router; address payable public _FeeAddress1; address payable public _FeeAddress2; address public uniswapV2Pair; uint public _buyFee = 10; uint public _sellFee = 10; uint public _feeRate = 9; uint public _maxTradeAmount; uint public _maxWalletHoldings; uint public _launchedAt; bool private _tradingOpen; bool private _inSwap; bool public _useImpactFeeSetter = true; struct User { uint buy; bool exists; } event FeeMultiplierUpdated(uint _multiplier); event ImpactFeeSetterUpdated(bool _usefeesetter); event FeeRateUpdated(uint _rate); event FeesUpdated(uint _buy, uint _sell); event FeeAddress1Updated(address _feewallet1); event FeeAddress2Updated(address _feewallet2); modifier lockTheSwap { _inSwap = true; _; _inSwap = false; } constructor (address payable FeeAddress1, address payable FeeAddress2) { _FeeAddress1 = FeeAddress1; _FeeAddress2 = FeeAddress2; _owned[address(this)] = _totalSupply; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[FeeAddress1] = true; _isExcludedFromFee[FeeAddress2] = true; emit Transfer(address(0), address(this), _totalSupply); } function balanceOf(address account) public view override returns (uint) { return _owned[account]; } function transfer(address recipient, uint amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function totalSupply() public pure override returns (uint) { return _totalSupply; } function allowance(address owner, address spender) public view override returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public override returns (bool) { if(_tradingOpen && !_isExcludedFromFee[recipient] && sender == uniswapV2Pair){ require (recipient == tx.origin, "pls no bot"); } _transfer(sender, recipient, amount); uint allowedAmount = _allowances[sender][_msgSender()] - amount; _approve(sender, _msgSender(), allowedAmount); return true; } function _approve(address owner, address spender, uint amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBot[to], "Transfer failed, blacklisted wallet."); bool isBuy = false; if(from != owner() && to != owner()) { // buy if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(_tradingOpen, "Trading not yet enabled."); require(block.timestamp != _launchedAt, "pls no snip"); if((_launchedAt + (24 hours)) > block.timestamp) { require((amount + balanceOf(address(to))) <= _maxWalletHoldings, "You can't own that many tokens at once."); // 5% } if(!cooldown[to].exists) { cooldown[to] = User(0,true); } if((_launchedAt + (120 seconds)) > block.timestamp) { require(amount <= _maxTradeAmount, "Exceeds maximum buy amount."); require(cooldown[to].buy < block.timestamp + (15 seconds), "Your buy cooldown has not expired."); } cooldown[to].buy = block.timestamp; isBuy = true; } // sell if(!_inSwap && _tradingOpen && from != uniswapV2Pair) { require(cooldown[from].buy < block.timestamp + (15 seconds), "Your sell cooldown has not expired."); uint contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0) { if(_useImpactFeeSetter) { if(contractTokenBalance > (balanceOf(uniswapV2Pair) * _feeRate) / 100) { contractTokenBalance = (balanceOf(uniswapV2Pair) * _feeRate) / 100; } } swapTokensForEth(contractTokenBalance); } uint contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } isBuy = false; } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee,isBuy); } function swapTokensForEth(uint tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint amount) private { _FeeAddress1.transfer(amount / 2); _FeeAddress2.transfer(amount / 2); } function _tokenTransfer(address sender, address recipient, uint amount, bool takefee, bool buy) private { (uint fee) = _getFee(takefee, buy); _transferStandard(sender, recipient, amount, fee); } function _getFee(bool takefee, bool buy) private view returns (uint) { uint fee = 0; if(takefee) { if(buy) { fee = _buyFee; } else { fee = _sellFee; } } return fee; } function _transferStandard(address sender, address recipient, uint amount, uint fee) private { (uint transferAmount, uint team) = _getValues(amount, fee); _owned[sender] = _owned[sender] - amount; _owned[recipient] = _owned[recipient] + transferAmount; _takeTeam(team); emit Transfer(sender, recipient, transferAmount); } function _getValues(uint amount, uint teamFee) private pure returns (uint, uint) { uint team = (amount * teamFee) / 100; uint transferAmount = amount - team; return (transferAmount, team); } function _takeTeam(uint team) private { _owned[address(this)] = _owned[address(this)] + team; } receive() external payable {} // external functions function addLiquidity() external onlyOwner() { require(!_tradingOpen, "Trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _totalSupply); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function openTrading() external onlyOwner() { require(!_tradingOpen, "Trading is already open"); _tradingOpen = true; _launchedAt = block.timestamp; _maxTradeAmount = 500000000000000 * 10**9; // .5% for first 2 minutes after launch _maxWalletHoldings = 2500000000000000 * 10**9; // 5% for first 24 hours } function manualswap() external { require(_msgSender() == _FeeAddress1); uint contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _FeeAddress1); uint contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function setFeeRate(uint rate) external { require(_msgSender() == _FeeAddress1); require(rate > 0, "Rate can't be zero"); // 100% is the common fee rate _feeRate = rate; emit FeeRateUpdated(_feeRate); } function setFees(uint buy, uint sell) external { require(_msgSender() == _FeeAddress1); require(buy <= 5); require(sell <= 5); _buyFee = buy; _sellFee = sell; emit FeesUpdated(_buyFee, _sellFee); } function isBot(address ad) public view returns (bool) { return _isBot[ad]; } function toggleImpactFee(bool onoff) external onlyOwner() { _useImpactFeeSetter = onoff; emit ImpactFeeSetterUpdated(_useImpactFeeSetter); } function updateFeeAddress1(address newAddress) external { require(_msgSender() == _FeeAddress1); _FeeAddress1 = payable(newAddress); emit FeeAddress1Updated(_FeeAddress1); } function setBot(address botwallet) external { require(_msgSender() == _FeeAddress1); _isBot[botwallet] = true; } function delBot(address botwallet) external { require(_msgSender() == _FeeAddress1); _isBot[botwallet] = false; } function updateFeeAddress2(address newAddress) external { require(_msgSender() == _FeeAddress2); _FeeAddress2 = payable(newAddress); emit FeeAddress2Updated(_FeeAddress2); } // view functions function thisBalance() public view returns (uint) { return balanceOf(address(this)); } function amountInPool() public view returns (uint) { return balanceOf(uniswapV2Pair); } }
100% is the common fee rate
function setFeeRate(uint rate) external { require(_msgSender() == _FeeAddress1); require(rate > 0, "Rate can't be zero"); _feeRate = rate; emit FeeRateUpdated(_feeRate); }
1,203,301
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } pragma solidity ^0.8.0; /** * @dev 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; } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: reflective.sol pragma solidity ^0.8.4; contract ReflectiveCollective is ERC721Enumerable, Ownable { using Address for address; using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; // Starting and stopping sale and presale bool public saleActive = false; bool public presaleActive = false; // Reserved for the team, customs, giveaways, collabs and so on. uint256 public reserved = 115; // Price of each token uint256 public price = 0.08 ether; // Maximum limit of tokens that can ever exist uint256 constant MAX_SUPPLY = 10000; // The base link that leads to the image / video of the token string public baseTokenURI; //to show moc string public blankURI; // List of addresses that have a number of reserved tokens for presale mapping(address => uint256) public presaleReserved; event Received(address, uint256); constructor(string memory newBaseURI) ERC721("Reflective Collective", "RC") { setBaseURI(newBaseURI); } // Override so the openzeppelin tokenURI() method will use this method to create the full tokenURI instead function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } // See which address owns which tokens function tokensOfOwner(address addr) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(addr); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(addr, i); } return tokensId; } //Mint function mint(uint256 amount) public payable { require( presaleActive == true || saleActive == true, "sale is not activated yet" ); if (presaleActive == true && saleActive == false) { mintPresale(amount); } if (saleActive == true && presaleActive == false) { mintToken(amount); } } // Exclusive presale minting function mintPresale(uint256 amount) internal { require(amount > 0, "amount should not be zero.."); // uint256 reservedAmt = presaleReserved[msg.sender]; require( amount <= presaleReserved[msg.sender], "mintPresale Erorr: minted reserved tokens or not allowed" ); require(presaleActive, "Presale isn't active"); require( _tokenIdCounter.current() + amount <= MAX_SUPPLY - reserved, "Can't mint more than max supply" ); require(msg.value == price * amount, "Wrong amount of ETH sent"); for (uint256 i = 1; i <= amount; i++) { _safeMint(msg.sender, _tokenIdCounter.current()); _tokenIdCounter.increment(); presaleReserved[msg.sender] -= 1; } } // Standard mint function1 function mintToken(uint256 amount) internal { require(amount <= 10, "Only 10 tokens are allowed to mint once"); require(msg.value == price * amount, "Wrong amount of ETH sent"); require(saleActive, "Sale isn't active"); require( _tokenIdCounter.current() + amount <= MAX_SUPPLY - reserved, "Can't mint more than max supply" ); payable(owner()).transfer(msg.value); for (uint256 i = 1; i <= amount; i++) { _safeMint(msg.sender, _tokenIdCounter.current()); _tokenIdCounter.increment(); } } //withdraw ethers() from contract onlyy Admin function withdrawfunds() public payable onlyOwner { require( msg.sender == owner(), "withdrawfunds: only Owner can call this function" ); require( address(this).balance != 0, "withdrawfunds :no balance is in contract" ); payable(owner()).transfer(address(this).balance); } function checkContractBalance() external view onlyOwner returns (uint256 balance) { return address(this).balance; } // Admin minting function to reserve tokens for the team, collabs, customs and giveaways function mintReserved(uint256 _amount) public onlyOwner { // Limited to a publicly set amount require(_amount > 0, "Invalid amount is given"); require(_amount <= reserved, "Can't reserve more than set amount"); reserved -= _amount; for (uint256 i = 1; i <= _amount; i++) { _safeMint(msg.sender, _tokenIdCounter.current()); _tokenIdCounter.increment(); } } // Edit reserved presale spots function editPresaleReserved(address[] memory _a, uint256 _amount) public onlyOwner { for (uint256 i; i < _a.length; i++) { presaleReserved[_a[i]] = _amount; } } // Start and stop presale function setPresaleActive(bool val) public onlyOwner { presaleActive = val; if (val == true) { saleActive = false; } } // Start and stop sale function setSaleActive(bool val) public onlyOwner { saleActive = val; if (val == true) { presaleActive = false; } } // Set new baseURI function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } // Set a different price in case ETH changes drastically function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } //get number of minted tokens function counter() public view returns (uint256) { return _tokenIdCounter.current() - 1; } //function to reveal the metadata of tokens function reveal() public onlyOwner { setBaseURI( "https://dyy85tm27l.execute-api.us-east-1.amazonaws.com/prod/api/token/" ); } receive() external payable { emit Received(msg.sender, msg.value); } //function to get return remainingTokens for minting function remainingTokens() public view returns(uint256){ return MAX_SUPPLY - reserved - _tokenIdCounter.current(); } }
function to get return remainingTokens for minting
function remainingTokens() public view returns(uint256){ return MAX_SUPPLY - reserved - _tokenIdCounter.current(); }
5,828,278
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul interface DharmaTradeReserveV15Interface { event Trade( address account, address suppliedAsset, address receivedAsset, address retainedAsset, uint256 suppliedAmount, uint256 recievedAmount, uint256 retainedAmount ); event RoleModified(Role indexed role, address account); event RolePaused(Role indexed role); event RoleUnpaused(Role indexed role); event EtherReceived(address sender, uint256 amount); event GasReserveRefilled(uint256 etherAmount); enum Role { // # DEPOSIT_MANAGER, // 0 ADJUSTER, // 1 WITHDRAWAL_MANAGER, // 2 RESERVE_TRADER, // 3 PAUSER, // 4 GAS_RESERVE_REFILLER // 5 } enum TradeType { DAI_TO_TOKEN, DAI_TO_ETH, ETH_TO_DAI, TOKEN_TO_DAI, ETH_TO_TOKEN, TOKEN_TO_ETH, TOKEN_TO_TOKEN } struct RoleStatus { address account; bool paused; } function tradeDaiForEtherV2( uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function tradeEtherForDaiV2( uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought); function tradeDaiForToken( address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function tradeTokenForDai( ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought); function tradeTokenForEther( ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function tradeEtherForToken( address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold); function tradeEtherForTokenUsingEtherizer( address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function tradeTokenForToken( ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function tradeTokenForTokenUsingReserves( ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function tradeDaiForEtherUsingReservesV2( uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function tradeEtherForDaiUsingReservesAndMintDDaiV2( uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function tradeDaiForTokenUsingReserves( address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function tradeTokenForDaiUsingReservesAndMintDDai( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function tradeTokenForEtherUsingReserves( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function tradeEtherForTokenUsingReserves( address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function finalizeEtherDeposit( address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external; function finalizeDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external; function finalizeDharmaDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external; function mint(uint256 daiAmount) external returns (uint256 dDaiMinted); function redeem(uint256 dDaiAmount) external returns (uint256 daiReceived); function tradeDDaiForUSDC( uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function tradeUSDCForDDai( uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function refillGasReserve(uint256 etherAmount) external; function withdrawUSDC(address recipient, uint256 usdcAmount) external; function withdrawDai(address recipient, uint256 daiAmount) external; function withdrawDharmaDai(address recipient, uint256 dDaiAmount) external; function withdrawUSDCToPrimaryRecipient(uint256 usdcAmount) external; function withdrawDaiToPrimaryRecipient(uint256 usdcAmount) external; function withdrawEther( address payable recipient, uint256 etherAmount ) external; function withdraw( ERC20Interface token, address recipient, uint256 amount ) external returns (bool success); function callAny( address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); function setDaiLimit(uint256 daiAmount) external; function setEtherLimit(uint256 daiAmount) external; function setPrimaryUSDCRecipient(address recipient) external; function setPrimaryDaiRecipient(address recipient) external; function setRole(Role role, address account) external; function removeRole(Role role) external; function pause(Role role) external; function unpause(Role role) external; function isPaused(Role role) external view returns (bool paused); function isRole(Role role) external view returns (bool hasRole); function isDharmaSmartWallet( address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet); function getDepositManager() external view returns (address depositManager); function getAdjuster() external view returns (address adjuster); function getReserveTrader() external view returns (address reserveTrader); function getWithdrawalManager() external view returns (address withdrawalManager); function getPauser() external view returns (address pauser); function getGasReserveRefiller() external view returns (address gasReserveRefiller); function getReserves() external view returns ( uint256 dai, uint256 dDai, uint256 dDaiUnderlying ); function getDaiLimit() external view returns ( uint256 daiAmount, uint256 dDaiAmount ); function getEtherLimit() external view returns (uint256 etherAmount); function getPrimaryUSDCRecipient() external view returns ( address recipient ); function getPrimaryDaiRecipient() external view returns ( address recipient ); function getImplementation() external view returns (address implementation); function getInstance() external pure returns (address instance); function getVersion() external view returns (uint256 version); } interface ERC20Interface { function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function allowance(address, address) external view returns (uint256); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); } interface DTokenInterface { function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); function redeemUnderlying(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); function balanceOf(address) external view returns (uint256); function balanceOfUnderlying(address) external view returns (uint256); function transfer(address, uint256) external returns (bool); function approve(address, uint256) external returns (bool); function exchangeRateCurrent() external view returns (uint256); } interface TradeHelperInterface { function tradeUSDCForDDai( uint256 amountUSDC, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function tradeDDaiForUSDC( uint256 amountDai, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function getExpectedDai(uint256 usdc) external view returns (uint256 dai); function getExpectedUSDC(uint256 dai) external view returns (uint256 usdc); } interface UniswapV2Interface { function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, 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 swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, 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 swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. * * In order to transfer ownership, a recipient must be specified, at which point * the specified recipient can call `acceptOwnership` and take ownership. */ contract TwoStepOwnable { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); address private _owner; address private _newPotentialOwner; /** * @dev Allows a new account (`newOwner`) to accept ownership. * Can only be called by the current owner. */ function transferOwnership(address newOwner) external onlyOwner { require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } /** * @dev Cancel a transfer of ownership to a new account. * Can only be called by the current owner. */ function cancelOwnershipTransfer() external onlyOwner { delete _newPotentialOwner; } /** * @dev Transfers ownership of the contract to the caller. * Can only be called by a new potential owner set by the current owner. */ function acceptOwnership() external { require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OwnershipTransferred(_owner, msg.sender); _owner = msg.sender; } /** * @dev Returns the address of the current owner. */ function owner() external view returns (address) { return _owner; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "TwoStepOwnable: caller is not the owner."); _; } } /** * @title DharmaTradeReserveV15ImplementationStaging * @author 0age * @notice This contract manages Dharma's reserves. It designates a collection of * "roles" - these are dedicated accounts that can be modified by the owner, and * that can trigger specific functionality on the reserve. These roles are: * - depositManager (0): initiates Eth / token transfers to smart wallets * - adjuster (1): mints / redeems Dai, and swaps USDC, for dDai * - withdrawalManager (2): initiates token transfers to recipients set by owner * - reserveTrader (3): initiates trades using funds held in reserve * - pauser (4): pauses any role (only the owner is then able to unpause it) * - gasReserveRefiller (5): transfers Ether to the Dharma Gas Reserve * * When finalizing deposits, the deposit manager must adhere to two constraints: * - it must provide "proof" that the recipient is a smart wallet by including * the initial user signing key used to derive the smart wallet address * - it must not attempt to transfer more Eth, Dai, or the Dai-equivalent * value of Dharma Dai, than the current "limit" set by the owner. * * Note that "proofs" can be validated via `isSmartWallet`. */ contract DharmaTradeReserveV15ImplementationStaging is DharmaTradeReserveV15Interface, TwoStepOwnable { using SafeMath for uint256; // Maintain a role status mapping with assigned accounts and paused states. mapping(uint256 => RoleStatus) private _roles; // Maintain a "primary recipient" the withdrawal manager can transfer Dai to. address private _primaryDaiRecipient; // Maintain a "primary recipient" the withdrawal manager can transfer USDC to. address private _primaryUSDCRecipient; // Maintain a maximum allowable transfer size (in Dai) for the deposit manager. uint256 private _daiLimit; // Maintain a maximum allowable transfer size (in Ether) for the deposit manager. uint256 private _etherLimit; bool private _originatesFromReserveTrader; // unused, don't change storage layout uint256 private constant _VERSION = 1015; // This contract interacts with USDC, Dai, and Dharma Dai. ERC20Interface internal constant _USDC = ERC20Interface( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); ERC20Interface internal constant _DAI = ERC20Interface( 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); ERC20Interface internal constant _ETHERIZER = ERC20Interface( 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); DTokenInterface internal constant _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 ); TradeHelperInterface internal constant _TRADE_HELPER = TradeHelperInterface( 0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d ); UniswapV2Interface internal constant _UNISWAP_ROUTER = UniswapV2Interface( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address internal constant _WETH = address( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ); address internal constant _GAS_RESERVE = address( 0x09cd826D4ABA4088E1381A1957962C946520952d // staging version ); // The "Create2 Header" is used to compute smart wallet deployment addresses. bytes21 internal constant _CREATE2_HEADER = bytes21( 0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory ); // The "Wallet creation code" header & footer are also used to derive wallets. bytes internal constant _WALLET_CREATION_CODE_HEADER = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; bytes28 internal constant _WALLET_CREATION_CODE_FOOTER = bytes28( 0x00000000000000000000000000000000000000000000000000000000 ); // Flag to trigger trade for USDC and retain full trade amount address internal constant _TRADE_FOR_USDC_AND_RETAIN_FLAG = address(uint160(-1)); // Include a payable fallback so that the contract can receive Ether payments. function () external payable { emit EtherReceived(msg.sender, msg.value); } function initialize() external onlyOwner { // Approve Uniswap router to transfer WETH on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(ERC20Interface(_WETH), uint256(-1)); } /** * @notice Pull in `daiAmount` Dai from the caller, trade it for Ether using * UniswapV2, and return `quotedEtherAmount` Ether to the caller. * @param daiAmount uint256 The amount of Dai to supply when trading for Ether. * @param quotedEtherAmount uint256 The amount of Ether to return to the caller. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Dai sold as part of the trade. */ function tradeDaiForEtherV2( uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _transferInToken(_DAI, msg.sender, daiAmount); // Trade Dai for Ether. totalDaiSold = _tradeDaiForEther( daiAmount, quotedEtherAmount, deadline, false ); } function tradeTokenForEther( ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought) { // Transfer the tokens from the caller and revert on failure. _transferInToken(token, msg.sender, tokenAmount); // Trade tokens for Ether. totalEtherBought = _tradeTokenForEther( token, tokenAmount, quotedEtherAmount, deadline, false ); // Transfer the quoted Ether amount to the caller. _transferEther(msg.sender, quotedEtherAmount); } function tradeDaiForToken( address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _transferInToken(_DAI, msg.sender, daiAmount); // Trade Dai for specified token. totalDaiSold = _tradeDaiForToken( token, daiAmount, quotedTokenAmount, deadline, routeThroughEther, false ); } /** * @notice Using `daiAmountFromReserves` Dai (note that dDai will be redeemed * if necessary), trade for Ether using UniswapV2. Only the owner or the trade * reserve role can call this function. Note that Dharma Dai will be redeemed * to cover the Dai if there is not enough currently in the contract. * @param daiAmountFromReserves the amount of Dai to take from reserves. * @param quotedEtherAmount uint256 The amount of Ether requested in the trade. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Ether bought as part of the trade. */ function tradeDaiForEtherUsingReservesV2( uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _redeemDDaiIfNecessary(daiAmountFromReserves); // Trade Dai for Ether using reserves. totalDaiSold = _tradeDaiForEther( daiAmountFromReserves, quotedEtherAmount, deadline, true ); } function tradeTokenForEtherUsingReserves( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherBought) { // Trade tokens for Ether using reserves. totalEtherBought = _tradeTokenForEther( token, tokenAmountFromReserves, quotedEtherAmount, deadline, true ); } /** * @notice Accept `msg.value` Ether from the caller, trade it for Dai using * UniswapV2, and return `quotedDaiAmount` Dai to the caller. * @param quotedDaiAmount uint256 The amount of Dai to return to the caller. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Dai bought as part of the trade. */ function tradeEtherForDaiV2( uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought) { // Trade Ether for Dai. totalDaiBought = _tradeEtherForDai( msg.value, quotedDaiAmount, deadline, false ); // Transfer the Dai to the caller and revert on failure. _transferToken(_DAI, msg.sender, quotedDaiAmount); } function tradeEtherForToken( address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold) { // Trade Ether for the specified token. totalEtherSold = _tradeEtherForToken( token, msg.value, quotedTokenAmount, deadline, false ); } function tradeEtherForTokenUsingEtherizer( address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold) { // Transfer the Ether from the caller and revert on failure. _transferInToken(_ETHERIZER, msg.sender, etherAmount); // Trade Ether for the specified token. totalEtherSold = _tradeEtherForToken( token, etherAmount, quotedTokenAmount, deadline, false ); } function tradeTokenForDai( ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought) { // Transfer the token from the caller and revert on failure. _transferInToken(token, msg.sender, tokenAmount); // Trade the token for Dai. totalDaiBought = _tradeTokenForDai( token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false ); // Transfer the quoted Dai amount to the caller and revert on failure. _transferToken(_DAI, msg.sender, quotedDaiAmount); } function tradeTokenForToken( ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold) { // Transfer the token from the caller and revert on failure. _transferInToken(tokenProvided, msg.sender, tokenProvidedAmount); totalTokensSold = _tradeTokenForToken( msg.sender, tokenProvided, tokenReceived, tokenProvidedAmount, quotedTokenReceivedAmount, deadline, routeThroughEther ); } function tradeTokenForTokenUsingReserves( ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalTokensSold) { totalTokensSold = _tradeTokenForToken( address(this), tokenProvidedFromReserves, tokenReceived, tokenProvidedAmountFromReserves, quotedTokenReceivedAmount, deadline, routeThroughEther ); } /** * @notice Using `etherAmountFromReserves`, trade for Dai using UniswapV2, * and use that Dai to mint Dharma Dai. * Only the owner or the trade reserve role can call this function. * @param etherAmountFromReserves the amount of Ether to take from reserves * and add to the provided amount. * @param quotedDaiAmount uint256 The amount of Dai requested in the trade. * @param deadline uint256 The timestamp the order is valid until. * @return The amount of Dai bought as part of the trade. */ function tradeEtherForDaiUsingReservesAndMintDDaiV2( uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade Ether for Dai using reserves. totalDaiBought = _tradeEtherForDai( etherAmountFromReserves, quotedDaiAmount, deadline, true ); // Mint dDai using the received Dai. totalDDaiMinted = _DDAI.mint(totalDaiBought); } function tradeEtherForTokenUsingReserves( address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) { // Trade Ether for token using reserves. totalEtherSold = _tradeEtherForToken( token, etherAmountFromReserves, quotedTokenAmount, deadline, true ); } function tradeDaiForTokenUsingReserves( address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _redeemDDaiIfNecessary(daiAmountFromReserves); // Trade Dai for token using reserves. totalDaiSold = _tradeDaiForToken( token, daiAmountFromReserves, quotedTokenAmount, deadline, routeThroughEther, true ); } function tradeTokenForDaiUsingReservesAndMintDDai( ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external onlyOwnerOr(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade the token for Dai using reserves. totalDaiBought = _tradeTokenForDai( token, tokenAmountFromReserves, quotedDaiAmount, deadline, routeThroughEther, true ); // Mint dDai using the received Dai. totalDDaiMinted = _DDAI.mint(totalDaiBought); } /** * @notice Transfer `daiAmount` Dai to `smartWallet`, providing the initial * user signing key `initialUserSigningKey` as proof that the specified smart * wallet is indeed a Dharma Smart Wallet - this assumes that the address is * derived and deployed using the Dharma Smart Wallet Factory V1. In addition, * the specified amount must be less than the configured limit amount. Only * the owner or the designated deposit manager role may call this function. * @param smartWallet address The smart wallet to transfer Dai to. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @param daiAmount uint256 The amount of Dai to transfer - this must be less * than the current limit. */ function finalizeDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external onlyOwnerOr(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ensureSmartWallet(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(daiAmount < _daiLimit, "Transfer size exceeds the limit."); // Transfer the Dai to the specified smart wallet. _transferToken(_DAI, smartWallet, daiAmount); } /** * @notice Transfer `dDaiAmount` Dharma Dai to `smartWallet`, providing the * initial user signing key `initialUserSigningKey` as proof that the * specified smart wallet is indeed a Dharma Smart Wallet - this assumes that * the address is derived and deployed using the Dharma Smart Wallet Factory * V1. In addition, the Dai equivalent value of the specified dDai amount must * be less than the configured limit amount. Only the owner or the designated * deposit manager role may call this function. * @param smartWallet address The smart wallet to transfer Dai to. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @param dDaiAmount uint256 The amount of Dharma Dai to transfer - the Dai * equivalent amount must be less than the current limit. */ function finalizeDharmaDaiDeposit( address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external onlyOwnerOr(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ensureSmartWallet(smartWallet, initialUserSigningKey); // Get the current dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Ensure that an exchange rate was actually returned. require(exchangeRate != 0, "Could not retrieve dDai exchange rate."); // Get the equivalent Dai amount of the transfer. uint256 daiEquivalent = (dDaiAmount.mul(exchangeRate)) / 1e18; // Ensure that the amount to transfer is lower than the limit. require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit."); // Transfer the dDai to the specified smart wallet. _transferToken(ERC20Interface(address(_DDAI)), smartWallet, dDaiAmount); } /** * @notice Transfer `etherAmount` Ether to `smartWallet`, providing the * initial user signing key `initialUserSigningKey` as proof that the * specified smart wallet is indeed a Dharma Smart Wallet - this assumes that * the address is derived and deployed using the Dharma Smart Wallet Factory * V1. In addition, the Ether amount must be less than the configured limit * amount. Only the owner or the designated deposit manager role may call this * function. * @param smartWallet address The smart wallet to transfer Ether to. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @param etherAmount uint256 The amount of Ether to transfer - this amount must be * less than the current limit. */ function finalizeEtherDeposit( address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external onlyOwnerOr(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ensureSmartWallet(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(etherAmount < _etherLimit, "Transfer size exceeds the limit."); // Transfer the Ether to the specified smart wallet. _transferEther(smartWallet, etherAmount); } /** * @notice Use `daiAmount` Dai mint Dharma Dai. Only the owner or the * designated adjuster role may call this function. * @param daiAmount uint256 The amount of Dai to supply when minting Dharma * Dai. * @return The amount of Dharma Dai minted. */ function mint( uint256 daiAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) { // Use the specified amount of Dai to mint dDai. dDaiMinted = _DDAI.mint(daiAmount); } /** * @notice Redeem `dDaiAmount` Dharma Dai for Dai. Only the owner or the * designated adjuster role may call this function. * @param dDaiAmount uint256 The amount of Dharma Dai to supply when redeeming * for Dai. * @return The amount of Dai received. */ function redeem( uint256 dDaiAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 daiReceived) { // Redeem the specified amount of dDai for Dai. daiReceived = _DDAI.redeem(dDaiAmount); } /** * @notice trade `usdcAmount` USDC for Dharma Dai. Only the owner or the designated * adjuster role may call this function. * @param usdcAmount uint256 The amount of USDC to supply when trading for Dharma Dai. * @param quotedDaiEquivalentAmount uint256 The expected DAI equivalent value of the * received dDai - this value is returned from the `getAndExpectedDai` view function * on the trade helper. * @return The amount of dDai received. */ function tradeUSDCForDDai( uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) { dDaiMinted = _TRADE_HELPER.tradeUSDCForDDai( usdcAmount, quotedDaiEquivalentAmount ); } /** * @notice tradeDDaiForUSDC `daiEquivalentAmount` Dai amount to trade in Dharma Dai * for USDC. Only the owner or the designated adjuster role may call this function. * @param daiEquivalentAmount uint256 The Dai equivalent amount to supply in Dharma * Dai when trading for USDC. * @param quotedUSDCAmount uint256 The expected USDC received in exchange for * dDai - this value is returned from the `getExpectedUSDC` view function on the * trade helper. * @return The amount of USDC received. */ function tradeDDaiForUSDC( uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 usdcReceived) { usdcReceived = _TRADE_HELPER.tradeDDaiForUSDC( daiEquivalentAmount, quotedUSDCAmount ); } function refillGasReserve(uint256 etherAmount) external onlyOwnerOr(Role.GAS_RESERVE_REFILLER) { // Transfer the Ether to the gas reserve. _transferEther(_GAS_RESERVE, etherAmount); emit GasReserveRefilled(etherAmount); } /** * @notice Transfer `usdcAmount` USDC for to the current primary recipient set by the * owner. Only the owner or the designated withdrawal manager role may call this function. * @param usdcAmount uint256 The amount of USDC to transfer to the primary recipient. */ function withdrawUSDCToPrimaryRecipient( uint256 usdcAmount ) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryUSDCRecipient; require( primaryRecipient != address(0), "No USDC primary recipient currently set." ); // Transfer the supplied USDC amount to the primary recipient. _transferToken(_USDC, primaryRecipient, usdcAmount); } /** * @notice Transfer `daiAmount` Dai for to the current primary recipient set by the * owner. Only the owner or the designated withdrawal manager role may call this function. * @param daiAmount uint256 The amount of Dai to transfer to the primary recipient. */ function withdrawDaiToPrimaryRecipient( uint256 daiAmount ) external onlyOwnerOr(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryDaiRecipient; require( primaryRecipient != address(0), "No Dai primary recipient currently set." ); // Transfer the supplied Dai amount to the primary recipient. _transferToken(_DAI, primaryRecipient, daiAmount); } /** * @notice Transfer `usdcAmount` USDC to `recipient`. Only the owner may call * this function. * @param recipient address The account to transfer USDC to. * @param usdcAmount uint256 The amount of USDC to transfer. */ function withdrawUSDC( address recipient, uint256 usdcAmount ) external onlyOwner { // Transfer the USDC to the specified recipient. _transferToken(_USDC, recipient, usdcAmount); } /** * @notice Transfer `daiAmount` Dai to `recipient`. Only the owner may call * this function. * @param recipient address The account to transfer Dai to. * @param daiAmount uint256 The amount of Dai to transfer. */ function withdrawDai( address recipient, uint256 daiAmount ) external onlyOwner { // Transfer the Dai to the specified recipient. _transferToken(_DAI, recipient, daiAmount); } /** * @notice Transfer `dDaiAmount` Dharma Dai to `recipient`. Only the owner may * call this function. * @param recipient address The account to transfer Dharma Dai to. * @param dDaiAmount uint256 The amount of Dharma Dai to transfer. */ function withdrawDharmaDai( address recipient, uint256 dDaiAmount ) external onlyOwner { // Transfer the dDai to the specified recipient. _transferToken(ERC20Interface(address(_DDAI)), recipient, dDaiAmount); } /** * @notice Transfer `etherAmount` Ether to `recipient`. Only the owner may * call this function. * @param recipient address The account to transfer Ether to. * @param etherAmount uint256 The amount of Ether to transfer. */ function withdrawEther( address payable recipient, uint256 etherAmount ) external onlyOwner { // Transfer the Ether to the specified recipient. _transferEther(recipient, etherAmount); } /** * @notice Transfer `amount` of ERC20 token `token` to `recipient`. Only the * owner may call this function. * @param token ERC20Interface The ERC20 token to transfer. * @param recipient address The account to transfer the tokens to. * @param amount uint256 The amount of tokens to transfer. * @return A boolean to indicate if the transfer was successful - note that * unsuccessful ERC20 transfers will usually revert. */ function withdraw( ERC20Interface token, address recipient, uint256 amount ) external onlyOwner returns (bool success) { // Transfer the token to the specified recipient. success = token.transfer(recipient, amount); } /** * @notice Call account `target`, supplying value `amount` and data `data`. * Only the owner may call this function. * @param target address The account to call. * @param amount uint256 The amount of ether to include as an endowment. * @param data bytes The data to include along with the call. * @return A boolean to indicate if the call was successful, as well as the * returned data or revert reason. */ function callAny( address payable target, uint256 amount, bytes calldata data ) external onlyOwner returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified data. (ok, returnData) = target.call.value(amount)(data); } /** * @notice Set `daiAmount` as the new limit on the size of finalized deposits. * Only the owner may call this function. * @param daiAmount uint256 The new limit on the size of finalized deposits. */ function setDaiLimit(uint256 daiAmount) external onlyOwner { // Set the new limit. _daiLimit = daiAmount; } /** * @notice Set `etherAmount` as the new limit on the size of finalized deposits. * Only the owner may call this function. * @param etherAmount uint256 The new limit on the size of finalized deposits. */ function setEtherLimit(uint256 etherAmount) external onlyOwner { // Set the new limit. _etherLimit = etherAmount; } /** * @notice Set `recipient` as the new primary recipient for USDC withdrawals. * Only the owner may call this function. * @param recipient address The new primary recipient. */ function setPrimaryUSDCRecipient(address recipient) external onlyOwner { // Set the new primary recipient. _primaryUSDCRecipient = recipient; } /** * @notice Set `recipient` as the new primary recipient for Dai withdrawals. * Only the owner may call this function. * @param recipient address The new primary recipient. */ function setPrimaryDaiRecipient(address recipient) external onlyOwner { // Set the new primary recipient. _primaryDaiRecipient = recipient; } /** * @notice Pause a currently unpaused role and emit a `RolePaused` event. Only * the owner or the designated pauser may call this function. Also, bear in * mind that only the owner may unpause a role once paused. * @param role The role to pause. */ function pause(Role role) external onlyOwnerOr(Role.PAUSER) { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(!storedRoleStatus.paused, "Role in question is already paused."); storedRoleStatus.paused = true; emit RolePaused(role); } /** * @notice Unpause a currently paused role and emit a `RoleUnpaused` event. * Only the owner may call this function. * @param role The role to pause. */ function unpause(Role role) external onlyOwner { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(storedRoleStatus.paused, "Role in question is already unpaused."); storedRoleStatus.paused = false; emit RoleUnpaused(role); } /** * @notice Set a new account on a given role and emit a `RoleModified` event * if the role holder has changed. Only the owner may call this function. * @param role The role that the account will be set for. * @param account The account to set as the designated role bearer. */ function setRole(Role role, address account) external onlyOwner { require(account != address(0), "Must supply an account."); _setRole(role, account); } /** * @notice Remove any current role bearer for a given role and emit a * `RoleModified` event if a role holder was previously set. Only the owner * may call this function. * @param role The role that the account will be removed from. */ function removeRole(Role role) external onlyOwner { _setRole(role, address(0)); } /** * @notice External view function to check whether or not the functionality * associated with a given role is currently paused or not. The owner or the * pauser may pause any given role (including the pauser itself), but only the * owner may unpause functionality. Additionally, the owner may call paused * functions directly. * @param role The role to check the pause status on. * @return A boolean to indicate if the functionality associated with the role * in question is currently paused. */ function isPaused(Role role) external view returns (bool paused) { paused = _isPaused(role); } /** * @notice External view function to check whether the caller is the current * role holder. * @param role The role to check for. * @return A boolean indicating if the caller has the specified role. */ function isRole(Role role) external view returns (bool hasRole) { hasRole = _isRole(role); } /** * @notice External view function to check whether a "proof" that a given * smart wallet is actually a Dharma Smart Wallet, based on the initial user * signing key, is valid or not. This proof only works when the Dharma Smart * Wallet in question is derived using V1 of the Dharma Smart Wallet Factory. * @param smartWallet address The smart wallet to check. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @return A boolean indicating if the specified smart wallet account is * indeed a smart wallet based on the specified initial user signing key. */ function isDharmaSmartWallet( address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet) { dharmaSmartWallet = _isSmartWallet(smartWallet, initialUserSigningKey); } /** * @notice External view function to check the account currently holding the * deposit manager role. The deposit manager can process standard deposit * finalization via `finalizeDaiDeposit` and `finalizeDharmaDaiDeposit`, but * must prove that the recipient is a Dharma Smart Wallet and adhere to the * current deposit size limit. * @return The address of the current deposit manager, or the null address if * none is set. */ function getDepositManager() external view returns (address depositManager) { depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account; } /** * @notice External view function to check the account currently holding the * adjuster role. The adjuster can exchange Dai in reserves for Dharma Dai and * vice-versa via minting or redeeming. * @return The address of the current adjuster, or the null address if none is * set. */ function getAdjuster() external view returns (address adjuster) { adjuster = _roles[uint256(Role.ADJUSTER)].account; } /** * @notice External view function to check the account currently holding the * reserve trader role. The reserve trader can trigger trades that utilize * reserves in addition to supplied funds, if any. * @return The address of the current reserve trader, or the null address if * none is set. */ function getReserveTrader() external view returns (address reserveTrader) { reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account; } /** * @notice External view function to check the account currently holding the * withdrawal manager role. The withdrawal manager can transfer USDC to the * "primary recipient" address set by the owner. * @return The address of the current withdrawal manager, or the null address * if none is set. */ function getWithdrawalManager() external view returns (address withdrawalManager) { withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account; } /** * @notice External view function to check the account currently holding the * pauser role. The pauser can pause any role from taking its standard action, * though the owner will still be able to call the associated function in the * interim and is the only entity able to unpause the given role once paused. * @return The address of the current pauser, or the null address if none is * set. */ function getPauser() external view returns (address pauser) { pauser = _roles[uint256(Role.PAUSER)].account; } function getGasReserveRefiller() external view returns (address gasReserveRefiller) { gasReserveRefiller = _roles[uint256(Role.GAS_RESERVE_REFILLER)].account; } /** * @notice External view function to check the current reserves held by this * contract. * @return The Dai and Dharma Dai reserves held by this contract, as well as * the Dai-equivalent value of the Dharma Dai reserves. */ function getReserves() external view returns ( uint256 dai, uint256 dDai, uint256 dDaiUnderlying ) { dai = _DAI.balanceOf(address(this)); dDai = _DDAI.balanceOf(address(this)); dDaiUnderlying = _DDAI.balanceOfUnderlying(address(this)); } /** * @notice External view function to check the current limit on deposit amount * enforced for the deposit manager when finalizing deposits, expressed in Dai * and in Dharma Dai. * @return The Dai and Dharma Dai limit on deposit finalization amount. */ function getDaiLimit() external view returns ( uint256 daiAmount, uint256 dDaiAmount ) { daiAmount = _daiLimit; dDaiAmount = (daiAmount.mul(1e18)).div(_DDAI.exchangeRateCurrent()); } /** * @notice External view function to check the current limit on deposit amount * enforced for the deposit manager when finalizing Ether deposits. * @return The Ether limit on deposit finalization amount. */ function getEtherLimit() external view returns (uint256 etherAmount) { etherAmount = _etherLimit; } /** * @notice External view function to check the address of the current * primary recipient for USDC. * @return The primary recipient for USDC. */ function getPrimaryUSDCRecipient() external view returns ( address recipient ) { recipient = _primaryUSDCRecipient; } /** * @notice External view function to check the address of the current * primary recipient for Dai. * @return The primary recipient for Dai. */ function getPrimaryDaiRecipient() external view returns ( address recipient ) { recipient = _primaryDaiRecipient; } /** * @notice External view function to check the current implementation * of this contract (i.e. the "logic" for the contract). * @return The current implementation for this contract. */ function getImplementation() external view returns ( address implementation ) { (bool ok, bytes memory returnData) = address( 0x481B1a16E6675D33f8BBb3a6A58F5a9678649718 ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } /** * @notice External pure function to get the address of the actual * contract instance (i.e. the "storage" foor this contract). * @return The address of this contract instance. */ function getInstance() external pure returns (address instance) { instance = address(0x09cd826D4ABA4088E1381A1957962C946520952d); } function getVersion() external view returns (uint256 version) { version = _VERSION; } function _grantUniswapRouterApprovalIfNecessary(ERC20Interface token, uint256 amount) internal { if (token.allowance(address(this), address(_UNISWAP_ROUTER)) < amount) { // Try removing approval for Uniswap router first as a workaround for unusual tokens. (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector( token.approve.selector, address(_UNISWAP_ROUTER), uint256(0) ) ); // Grant approval for Uniswap router to transfer tokens on behalf of this contract. (success, data) = address(token).call( abi.encodeWithSelector( token.approve.selector, address(_UNISWAP_ROUTER), uint256(-1) ) ); if (!success) { // Some really janky tokens only allow setting approval up to current balance. (success, data) = address(token).call( abi.encodeWithSelector( token.approve.selector, address(_UNISWAP_ROUTER), amount ) ); } require( success && (data.length == 0 || abi.decode(data, (bool))), "Token approval for Uniswap router failed." ); } } function _tradeEtherForDai( uint256 etherAmount, uint256 quotedDaiAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Establish path from Ether to Dai. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( _WETH, address(_DAI), false ); // Trade Ether for Dai on Uniswap (send to this contract). amounts = _UNISWAP_ROUTER.swapExactETHForTokens.value(etherAmount)( quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[1]; _fireTradeEvent( fromReserves, TradeType.ETH_TO_DAI, address(0), etherAmount, quotedDaiAmount, totalDaiBought.sub(quotedDaiAmount) ); } function _tradeDaiForEther( uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path from Dai to Ether. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(_DAI), _WETH, false ); // Trade Dai for quoted Ether amount on Uniswap (send to appropriate recipient). amounts = _UNISWAP_ROUTER.swapTokensForExactETH( quotedEtherAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _fireTradeEvent( fromReserves, TradeType.DAI_TO_ETH, address(0), daiAmount, quotedEtherAmount, daiAmount.sub(totalDaiSold) ); } /** * @notice Internal trade function. If token is _TRADE_FOR_USDC_AND_RETAIN_FLAG, * trade for USDC and retain the full output amount by replacing the recipient * ("to" input) on the swapETHForExactTokens call. */ function _tradeEtherForToken( address tokenReceivedOrUSDCFlag, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherSold) { // Set swap target token address tokenReceived = tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG ? address(_USDC) : tokenReceivedOrUSDCFlag; // Establish path from Ether to token. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( _WETH, tokenReceived, false ); // Trade Ether for quoted token amount on Uniswap and send to appropriate recipient. amounts = _UNISWAP_ROUTER.swapETHForExactTokens.value(etherAmount)( quotedTokenAmount, path, fromReserves || tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG ? address(this) : msg.sender, deadline ); totalEtherSold = amounts[0]; _fireTradeEvent( fromReserves, TradeType.ETH_TO_TOKEN, tokenReceivedOrUSDCFlag, etherAmount, quotedTokenAmount, etherAmount.sub(totalEtherSold) ); } function _tradeTokenForEther( ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(token, tokenAmount); // Establish path from target token to Ether. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(token), _WETH, false ); // Trade tokens for quoted Ether amount on Uniswap (send to this contract). amounts = _UNISWAP_ROUTER.swapExactTokensForETH( tokenAmount, quotedEtherAmount, path, address(this), deadline ); totalEtherBought = amounts[1]; _fireTradeEvent( fromReserves, TradeType.TOKEN_TO_ETH, address(token), tokenAmount, quotedEtherAmount, totalEtherBought.sub(quotedEtherAmount) ); } function _tradeDaiForToken( address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path (direct or routed through Ether) from Dai to target token. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(_DAI), address(token), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap and send to appropriate recipient. amounts = _UNISWAP_ROUTER.swapTokensForExactTokens( quotedTokenAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _fireTradeEvent( fromReserves, TradeType.DAI_TO_TOKEN, address(token), daiAmount, quotedTokenAmount, daiAmount.sub(totalDaiSold) ); } function _tradeTokenForDai( ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(token, tokenAmount); // Establish path (direct or routed through Ether) from target token to Dai. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(token), address(_DAI), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap (send to this contract). amounts = _UNISWAP_ROUTER.swapExactTokensForTokens( tokenAmount, quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[path.length - 1]; _fireTradeEvent( fromReserves, TradeType.TOKEN_TO_DAI, address(token), tokenAmount, quotedDaiAmount, totalDaiBought.sub(quotedDaiAmount) ); } /** * @notice Internal trade function. If tokenReceived is _TRADE_FOR_USDC_AND_RETAIN_FLAG, * trade for USDC and retain the full output amount by replacing the recipient * ("to" input) on the swapTokensForExactTokens call. */ function _tradeTokenForToken( address account, ERC20Interface tokenProvided, address tokenReceivedOrUSDCFlag, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) internal returns (uint256 totalTokensSold) { uint256 retainedAmount; address tokenRecieved; address recipient; // Approve Uniswap router to transfer tokens on behalf of this contract. _grantUniswapRouterApprovalIfNecessary(tokenProvided, tokenProvidedAmount); // Set recipient, swap target token if (tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG) { recipient = address(this); tokenRecieved = address(_USDC); } else { recipient = account; tokenRecieved = tokenReceivedOrUSDCFlag; } if (routeThroughEther == false) { // Establish direct path between tokens. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(tokenProvided), tokenRecieved, false ); // Trade for the quoted token amount on Uniswap and send to recipient. amounts = _UNISWAP_ROUTER.swapTokensForExactTokens( quotedTokenReceivedAmount, tokenProvidedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = tokenProvidedAmount.sub(totalTokensSold); } else { // Establish path between provided token and WETH. (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( address(tokenProvided), _WETH, false ); // Trade all provided tokens for WETH on Uniswap and send to this contract. amounts = _UNISWAP_ROUTER.swapExactTokensForTokens( tokenProvidedAmount, 0, path, address(this), deadline ); retainedAmount = amounts[1]; // Establish path between WETH and received token. (path, amounts) = _createPathAndAmounts( _WETH, tokenRecieved, false ); // Trade bought WETH for received token on Uniswap and send to recipient. amounts = _UNISWAP_ROUTER.swapTokensForExactTokens( quotedTokenReceivedAmount, retainedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = retainedAmount.sub(totalTokensSold); } emit Trade( account, address(tokenProvided), tokenReceivedOrUSDCFlag, routeThroughEther ? _WETH : address(tokenProvided), tokenProvidedAmount, quotedTokenReceivedAmount, retainedAmount ); } /** * @notice Internal function to set a new account on a given role and emit a * `RoleModified` event if the role holder has changed. * @param role The role that the account will be set for. Permitted roles are * deposit manager (0), adjuster (1), and pauser (2). * @param account The account to set as the designated role bearer. */ function _setRole(Role role, address account) internal { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; if (account != storedRoleStatus.account) { storedRoleStatus.account = account; emit RoleModified(role, account); } } function _fireTradeEvent( bool fromReserves, TradeType tradeType, address token, uint256 suppliedAmount, uint256 receivedAmount, uint256 retainedAmount ) internal { uint256 t = uint256(tradeType); emit Trade( fromReserves ? address(this) : msg.sender, t < 2 ? address(_DAI) : (t % 2 == 0 ? address(0) : token), (t > 1 && t < 4) ? address(_DAI) : (t % 2 == 0 ? token : address(0)), t < 4 ? address(_DAI) : address(0), suppliedAmount, receivedAmount, retainedAmount ); } /** * @notice Internal view function to check whether the caller is the current * role holder. * @param role The role to check for. * @return A boolean indicating if the caller has the specified role. */ function _isRole(Role role) internal view returns (bool hasRole) { hasRole = msg.sender == _roles[uint256(role)].account; } /** * @notice Internal view function to check whether the given role is paused or * not. * @param role The role to check for. * @return A boolean indicating if the specified role is paused or not. */ function _isPaused(Role role) internal view returns (bool paused) { paused = _roles[uint256(role)].paused; } /** * @notice Internal view function to enforce that the given initial user signing * key resolves to the given smart wallet when deployed through the Dharma Smart * Wallet Factory V1. (staging version) * @param smartWallet address The smart wallet. * @param initialUserSigningKey address The initial user signing key. */ function _isSmartWallet( address smartWallet, address initialUserSigningKey ) internal pure returns (bool) { // Derive the keccak256 hash of the smart wallet initialization code. bytes32 initCodeHash = keccak256( abi.encodePacked( _WALLET_CREATION_CODE_HEADER, initialUserSigningKey, _WALLET_CREATION_CODE_FOOTER ) ); // Attempt to derive a smart wallet address that matches the one provided. address target; for (uint256 nonce = 0; nonce < 10; nonce++) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using all inputs. abi.encodePacked( // pack all inputs to the hash together. _CREATE2_HEADER, // pass in control character + factory address. nonce, // pass in current nonce as the salt. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); // Exit early if the provided smart wallet matches derived target address. if (target == smartWallet) { return true; } // Otherwise, increment the nonce and derive a new salt. nonce++; } // Explicity recognize no target was found matching provided smart wallet. return false; } function _redeemDDaiIfNecessary(uint256 daiAmountFromReserves) internal { uint256 daiBalance = _DAI.balanceOf(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _DDAI.redeemUnderlying(additionalDaiRequired); } } function _transferToken(ERC20Interface token, address to, uint256 amount) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.transfer.selector, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer out failed.' ); } function _transferEther(address recipient, uint256 etherAmount) internal { // Send quoted Ether amount to recipient and revert with reason on failure. (bool ok, ) = recipient.call.value(etherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function _transferInToken(ERC20Interface token, address from, uint256 amount) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.transferFrom.selector, from, address(this), amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer in failed.' ); } function _ensureSmartWallet( address smartWallet, address initialUserSigningKey ) internal pure { require( _isSmartWallet(smartWallet, initialUserSigningKey), "Could not resolve smart wallet using provided signing key." ); } function _createPathAndAmounts( address start, address end, bool routeThroughEther ) internal pure returns (address[] memory, uint256[] memory) { uint256 pathLength = routeThroughEther ? 3 : 2; address[] memory path = new address[](pathLength); path[0] = start; if (routeThroughEther) { path[1] = _WETH; } path[pathLength - 1] = end; return (path, new uint256[](pathLength)); } /** * @notice Modifier that throws if called by any account other than the owner * or the supplied role, or if the caller is not the owner and the role in * question is paused. * @param role The role to require unless the caller is the owner. */ modifier onlyOwnerOr(Role role) { if (!isOwner()) { require(_isRole(role), "Caller does not have a required role."); require(!_isPaused(role), "Role in question is currently paused."); } _; } }
trade `usdcAmount` USDC for Dharma Dai. Only the owner or the designated adjuster role may call this function. usdcAmount uint256 The amount of USDC to supply when trading for Dharma Dai. quotedDaiEquivalentAmount uint256 The expected DAI equivalent value of the received dDai - this value is returned from the `getAndExpectedDai` view function on the trade helper. return The amount of dDai received./
function tradeUSDCForDDai( uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external onlyOwnerOr(Role.ADJUSTER) returns (uint256 dDaiMinted) { dDaiMinted = _TRADE_HELPER.tradeUSDCForDDai( usdcAmount, quotedDaiEquivalentAmount ); }
606,952
pragma solidity 0.4.25; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. 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. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match &#39;LP\x01&#39; (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if &#39;result&#39; is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let&#39;s do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity&#39;s ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don&#39;t update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can&#39;t access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // &#39;mload&#39; will pad with zeroes if we overread. // There is no &#39;mload8&#39; to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // &#39;byte&#39; is not working due to the Solidity parser, so lets // use the second best option, &#39;and&#39; // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { mapping(address => bool) owners; event OwnerAdded(address indexed newOwner); event OwnerDeleted(address indexed owner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owners[msg.sender] = true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(msg.sender)); _; } function addOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0)); owners[_newOwner] = true; emit OwnerAdded(_newOwner); } function delOwner(address _owner) external onlyOwner { require(owners[_owner]); owners[_owner] = false; emit OwnerDeleted(_owner); } function isOwner(address _owner) public view returns (bool) { return owners[_owner]; } } contract ERC20 { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function ownerTransfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); function unpause() public returns (bool); } library SafeERC20 { function safeTransfer(ERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeOwnerTransfer(ERC20 token, address to, uint256 value) internal { require(token.ownerTransfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using &#39;super&#39; where appropiate to concatenate * behavior. */ contract Crowdsale is Ownable, usingOraclize{ using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; address public wallet; address public reserveFund; uint256 public openingTime; uint256 public closingTime; uint256 public cap; uint256 public tokensSold; uint256 public tokenPriceInWei; bool public isFinalized = false; // Amount of wei raised uint256 public weiRaised; string public oraclize_url = "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0"; struct Stage { uint stopDay; uint bonus1; uint bonus2; uint bonus3; } mapping (uint => Stage) public stages; uint public stageCount; uint public currentStage; mapping (bytes32 => bool) public pendingQueries; mapping (address => bool) public KYC; uint public oraclizeBalance; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 tokens, uint256 bonus); event Finalized(); event NewOraclizeQuery(string description); event NewKrakenPriceTicker(string price); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } constructor(address _wallet, ERC20 _token, uint256 _cap, uint256 _openingTime, uint256 _closingTime, address _reserveFund, uint256 _tokenPriceInWei) public { require(_wallet != address(0)); require(_token != address(0)); require(_reserveFund != address(0)); require(_openingTime >= now); require(_closingTime >= _openingTime); require(_cap > 0); require(_tokenPriceInWei > 0); wallet = _wallet; token = _token; reserveFund = _reserveFund; cap = _cap; openingTime = _openingTime; closingTime = _closingTime; tokenPriceInWei = _tokenPriceInWei; currentStage = 1; addStage(openingTime + 1 days, 2000, 2250, 2500); addStage(openingTime + 7 days, 1500, 1750, 2000); addStage(openingTime + 14 days, 500, 750, 1000); addStage(openingTime + 21 days, 100, 100, 100); addStage(openingTime + 28 days, 0, 0, 0); oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } function __callback(bytes32 myid, string result, bytes proof) public { if (msg.sender != oraclize_cbAddress()) revert(); require (pendingQueries[myid] == true); proof; emit NewKrakenPriceTicker(result); uint USD = parseInt(result); tokenPriceInWei = 1 ether / USD; updatePrice(); delete pendingQueries[myid]; } function setTokenPrice(uint _price) onlyOwner public { tokenPriceInWei = _price; } function updatePrice() public payable { oraclizeBalance = oraclizeBalance.add(msg.value); uint queryPrice = oraclize_getPrice("URL"); if (queryPrice > address(this).balance) { emit NewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit NewOraclizeQuery("Oraclize query was sent, standing by for the answer.."); bytes32 queryId = oraclize_query(14400, "URL", oraclize_url); pendingQueries[queryId] = true; oraclizeBalance = oraclizeBalance.sub(queryPrice); } } function addStage(uint _stopDay, uint _bonus1, uint _bonus2, uint _bonus3) onlyOwner public { require(_stopDay > stages[stageCount].stopDay); stageCount++; stages[stageCount].stopDay = _stopDay; stages[stageCount].bonus1 = _bonus1; stages[stageCount].bonus2 = _bonus2; stages[stageCount].bonus3 = _bonus3; if (closingTime < _stopDay) { closingTime = _stopDay; } } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint tokens = 0; uint bonusTokens = 0; uint totalTokens = 0; (tokens, bonusTokens, totalTokens) = _getTokenAmount(weiAmount); _validatePurchase(tokens); uint256 price = tokens.div(1 ether).mul(tokenPriceInWei); uint256 _diff = weiAmount.sub(price); if (_diff > 0) { weiAmount = weiAmount.sub(_diff); msg.sender.transfer(_diff); } _processPurchase(_beneficiary, totalTokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens, bonusTokens); _updateState(weiAmount, totalTokens); _forwardFunds(weiAmount); } function manualSale(address _beneficiary, uint256 _tokens) onlyOwner external { require(_beneficiary != address(0)); require(tokensSold.add(_tokens) <= cap); uint256 weiAmount = _tokens.mul(tokenPriceInWei); _processPurchase(_beneficiary, _tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, _tokens, 0); _updateState(weiAmount, _tokens); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) onlyWhileOpen internal view{ require(_beneficiary != address(0)); require(KYC[_beneficiary]); require(_weiAmount != 0); require(tokensSold < cap); } function _validatePurchase(uint256 _tokens) internal view { require(_tokens >= 50 ether && _tokens <= 100000 ether); require(tokensSold.add(_tokens) <= cap); } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.safeOwnerTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal returns (uint,uint,uint) { uint tokens = _weiAmount.div(tokenPriceInWei).mul(1 ether); if (stages[currentStage].stopDay <= now) { _updateCurrentStage(); } uint bonus = 0; if (_weiAmount < 10 ether) { bonus = stages[currentStage].bonus1; } if (_weiAmount >= 10 ether && _weiAmount < 100 ether) { bonus = stages[currentStage].bonus2; } if (_weiAmount >= 100 ether) { bonus = stages[currentStage].bonus3; } bonus = tokens.mul(bonus).div(10000); uint total = tokens.add(bonus); if (tokensSold.add(total) > cap) { total = cap.sub(tokensSold); bonus = total.mul(bonus).div(10000 + bonus); tokens = total.sub(bonus); } return (tokens, bonus, total); } function _updateCurrentStage() internal { for (uint i = currentStage; i <= stageCount; i++) { if (stages[i].stopDay > now) { currentStage = i; break; } } } function _updateState(uint256 _weiAmount, uint256 _tokens) internal { weiRaised = weiRaised.add(_weiAmount); tokensSold = tokensSold.add(_tokens); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds(uint _weiAmount) internal { wallet.transfer(_weiAmount); } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed() || capReached()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { if (token.balanceOf(this) > 0) { token.safeOwnerTransfer(reserveFund, token.balanceOf(this)); } require(token.unpause()); } //1% - 100, 10% - 1000 50% - 5000 function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(10000); return (_amount); } function addKYC(address _user) onlyOwner public { KYC[_user] = true; } function delKYC(address _user) onlyOwner public { KYC[_user] = false; } function addBalanceForOraclize() payable external { oraclizeBalance = oraclizeBalance.add(msg.value); } function withdrawBalance(address _to) onlyOwner external { require(_to != address(0)); require(address(this).balance > 0); oraclizeBalance = 0; _to.transfer(address(this).balance); } function setGasPrice(uint _newPrice) onlyOwner public { oraclize_setCustomGasPrice(_newPrice * 1 wei); } function setOraclizeUrl(string _url) onlyOwner public { oraclize_url = _url; } }
Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. _beneficiary Address performing the token purchase _weiAmount Value in wei involved in the purchase/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) onlyWhileOpen internal view{ require(_beneficiary != address(0)); require(KYC[_beneficiary]); require(_weiAmount != 0); require(tokensSold < cap); }
6,785,036
// SPDX-License-Identifier: MIT /** Forked From Core + Orb. Website: https://corb.xyz */ pragma solidity 0.6.12; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c;} function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow");} function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c;} function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) {return 0;} uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c;} function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero");} function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c;} function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero");} function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b;} } 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); function mint(address account, uint256 amount) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface Uniswap{ function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function addLiquidityETH(address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external payable returns (uint amountToken, uint amountETH, uint liquidity); function getPair(address tokenA, address tokenB) external view returns (address pair); function WETH() external pure returns (address); } interface Pool{ function primary() external view returns (address); } contract Poolable{ address payable internal constant _POOLADDRESS = 0x0211061ffDbEcC27D75e5Ed06D41E4Aa25e2288A; function primary() private view returns (address) { return Pool(_POOLADDRESS).primary(); } modifier onlyPrimary() { require(msg.sender == primary(), "Caller is not primary"); _; } } contract Staker is Poolable{ using SafeMath for uint256; uint constant internal DECIMAL = 10**18; uint constant public INF = 33136721748; uint private _rewardValue = 10**21; mapping (address => uint256) public timePooled; mapping (address => uint256) private internalTime; mapping (address => uint256) private LPTokenBalance; mapping (address => uint256) private rewards; mapping (address => uint256) private referralEarned; address public corbAddress; address constant public UNIROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address constant public FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public WETHAddress = Uniswap(UNIROUTER).WETH(); bool private _unchangeable = false; bool private _tokenAddressGiven = false; bool public priceCapped = true; uint public creationTime = now; receive() external payable { if(msg.sender != UNIROUTER){ stake(); } } function sendValue(address payable recipient, uint256 amount) internal { (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } //If true, no changes can be made function unchangeable() public view returns (bool){ return _unchangeable; } function rewardValue() public view returns (uint){ return _rewardValue; } //THE ONLY ADMIN FUNCTIONS vvvv //After this is called, no changes can be made function makeUnchangeable() public onlyPrimary{ _unchangeable = true; } //Can only be called once to set token address function setTokenAddress(address input) public onlyPrimary{ require(!_tokenAddressGiven, "Function was already called"); _tokenAddressGiven = true; corbAddress = input; } //Set reward value that has high APY, can't be called if makeUnchangeable() was called function updateRewardValue(uint input) public onlyPrimary { require(!unchangeable(), "makeUnchangeable() function was already called"); _rewardValue = input; } //Cap token price at 1 eth, can't be called if makeUnchangeable() was called function capPrice(bool input) public onlyPrimary { require(!unchangeable(), "makeUnchangeable() function was already called"); priceCapped = input; } function withdrawfromcontract(address _selfdroptoken,uint256 amount) public onlyPrimary { require(_selfdroptoken!=address(0)); IERC20(_selfdroptoken).transfer(msg.sender,amount); } //THE ONLY ADMIN FUNCTIONS ^^^^ function sqrt(uint y) public pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function stake() public payable{ address staker = msg.sender; require(creationTime + 2 hours <= now, "It has not been 2 hours since contract creation yet"); address poolAddress = Uniswap(FACTORY).getPair(corbAddress, WETHAddress); if(price() >= (1.05 * 10**18) && priceCapped){ uint t = IERC20(corbAddress).balanceOf(poolAddress); //token in uniswap uint a = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap uint x = (sqrt(9*t*t + 3988000*a*t) - 1997*t)/1994; IERC20(corbAddress).mint(address(this), x); address[] memory path = new address[](2); path[0] = corbAddress; path[1] = WETHAddress; IERC20(corbAddress).approve(UNIROUTER, x); Uniswap(UNIROUTER).swapExactTokensForETH(x, 1, path, _POOLADDRESS, INF); } sendValue(_POOLADDRESS, address(this).balance/2); uint ethAmount = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap uint tokenAmount = IERC20(corbAddress).balanceOf(poolAddress); //token in uniswap uint toMint = (address(this).balance.mul(tokenAmount)).div(ethAmount); IERC20(corbAddress).mint(address(this), toMint); uint poolTokenAmountBefore = IERC20(poolAddress).balanceOf(address(this)); uint amountTokenDesired = IERC20(corbAddress).balanceOf(address(this)); IERC20(corbAddress).approve(UNIROUTER, amountTokenDesired ); //allow pool to get tokens Uniswap(UNIROUTER).addLiquidityETH{ value: address(this).balance }(corbAddress, amountTokenDesired, 1, 1, address(this), INF); uint poolTokenAmountAfter = IERC20(poolAddress).balanceOf(address(this)); uint poolTokenGot = poolTokenAmountAfter.sub(poolTokenAmountBefore); rewards[staker] = rewards[staker].add(viewRecentRewardTokenAmount(staker)); timePooled[staker] = now; internalTime[staker] = now; LPTokenBalance[staker] = LPTokenBalance[staker].add(poolTokenGot); } function withdrawLPTokens(uint amount) public { require(timePooled[msg.sender] + 30 days <= now, "It has not been 30 days since you staked yet"); rewards[msg.sender] = rewards[msg.sender].add(viewRecentRewardTokenAmount(msg.sender)); LPTokenBalance[msg.sender] = LPTokenBalance[msg.sender].sub(amount); address poolAddress = Uniswap(FACTORY).getPair(corbAddress, WETHAddress); IERC20(poolAddress).transfer(msg.sender, amount); internalTime[msg.sender] = now; } function withdrawRewardTokens(uint amount) public { require(timePooled[msg.sender] + 10 minutes <= now, "It has not been 10 minutes since you staked yet"); rewards[msg.sender] = rewards[msg.sender].add(viewRecentRewardTokenAmount(msg.sender)); internalTime[msg.sender] = now; uint removeAmount = ethtimeCalc(amount); rewards[msg.sender] = rewards[msg.sender].sub(removeAmount); // TETHERED uint256 withdrawable = tetheredReward(amount); IERC20(corbAddress).mint(msg.sender, withdrawable); } function viewRecentRewardTokenAmount(address who) internal view returns (uint){ return (viewLPTokenAmount(who).mul( now.sub(internalTime[who]) )); } function viewRewardTokenAmount(address who) public view returns (uint){ return earnCalc( rewards[who].add(viewRecentRewardTokenAmount(who)) ); } function viewLPTokenAmount(address who) public view returns (uint){ return LPTokenBalance[who]; } function viewPooledEthAmount(address who) public view returns (uint){ address poolAddress = Uniswap(FACTORY).getPair(corbAddress, WETHAddress); uint ethAmount = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap return (ethAmount.mul(viewLPTokenAmount(who))).div(IERC20(poolAddress).totalSupply()); } function viewPooledTokenAmount(address who) public view returns (uint){ address poolAddress = Uniswap(FACTORY).getPair(corbAddress, WETHAddress); uint tokenAmount = IERC20(corbAddress).balanceOf(poolAddress); //token in uniswap return (tokenAmount.mul(viewLPTokenAmount(who))).div(IERC20(poolAddress).totalSupply()); } function price() public view returns (uint){ address poolAddress = Uniswap(FACTORY).getPair(corbAddress, WETHAddress); uint ethAmount = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap uint tokenAmount = IERC20(corbAddress).balanceOf(poolAddress); //token in uniswap return (DECIMAL.mul(ethAmount)).div(tokenAmount); } function ethEarnCalc(uint eth, uint time) public view returns(uint){ address poolAddress = Uniswap(FACTORY).getPair(corbAddress, WETHAddress); uint totalEth = IERC20(WETHAddress).balanceOf(poolAddress); //Eth in uniswap uint totalLP = IERC20(poolAddress).totalSupply(); uint LP = ((eth/2)*totalLP)/totalEth; return earnCalc(LP * time); } function earnCalc(uint LPTime) public view returns(uint){ return ( rewardValue().mul(LPTime) ) / ( 31557600 * DECIMAL ); } function ethtimeCalc(uint corb) internal view returns(uint){ return ( corb.mul(31557600 * DECIMAL) ).div( rewardValue() ); } // Get amount of tethered rewards function tetheredReward(uint256 _amount) public view returns (uint256) { if (now >= timePooled[msg.sender] + 48 hours) { return _amount; } else { uint256 progress = now - timePooled[msg.sender]; uint256 total = 48 hours; uint256 ratio = progress.mul(1e6).div(total); return _amount.mul(ratio).div(1e6); } } }
Get amount of tethered rewards
function tetheredReward(uint256 _amount) public view returns (uint256) { if (now >= timePooled[msg.sender] + 48 hours) { return _amount; uint256 progress = now - timePooled[msg.sender]; uint256 total = 48 hours; uint256 ratio = progress.mul(1e6).div(total); return _amount.mul(ratio).div(1e6); } }
259,541
./full_match/137/0x6f073ff0728331D752F08a0429011225b19E1630/sources/browser/tests/DoTxLibOfficielOneFile.sol
Let owner withdraw Link owned by the contract/
function withdrawLink() public onlyOwner{ LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(owner(), link.balanceOf(address(this))), "Unable to transfer"); }
4,686,961
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import {ISynthereumFinder} from './interfaces/IFinder.sol'; import {ISynthereumDeployer} from './interfaces/IDeployer.sol'; import { ISynthereumFactoryVersioning } from './interfaces/IFactoryVersioning.sol'; import {ISynthereumRegistry} from './registries/interfaces/IRegistry.sol'; import {ISynthereumManager} from './interfaces/IManager.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IDeploymentSignature} from './interfaces/IDeploymentSignature.sol'; import { ISynthereumPoolWithDerivativeDeployment } from '../synthereum-pool/common/interfaces/IPoolWithDerivativeDeployment.sol'; import { IDerivativeDeployment } from '../derivative/common/interfaces/IDerivativeDeployment.sol'; import { ISelfMintingDerivativeDeployment } from '../derivative/self-minting/common/interfaces/ISelfMintingDerivativeDeployment.sol'; import {IRole} from '../base/interfaces/IRole.sol'; import {SynthereumInterfaces, FactoryInterfaces} from './Constants.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; import { EnumerableSet } from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; import {Lockable} from '@uma/core/contracts/common/implementation/Lockable.sol'; import { AccessControlEnumerable } from '@openzeppelin/contracts/access/AccessControlEnumerable.sol'; contract SynthereumDeployer is ISynthereumDeployer, AccessControlEnumerable, Lockable { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer'); bytes32 private constant ADMIN_ROLE = 0x00; bytes32 private constant POOL_ROLE = keccak256('Pool'); bytes32 private constant MINTER_ROLE = keccak256('Minter'); bytes32 private constant BURNER_ROLE = keccak256('Burner'); //Describe role structure struct Roles { address admin; address maintainer; } //---------------------------------------- // State variables //---------------------------------------- ISynthereumFinder public synthereumFinder; //---------------------------------------- // Events //---------------------------------------- event PoolDeployed( uint8 indexed poolVersion, address indexed derivative, address indexed newPool ); event DerivativeDeployed( uint8 indexed derivativeVersion, address indexed pool, address indexed newDerivative ); event SelfMintingDerivativeDeployed( uint8 indexed selfMintingDerivativeVersion, address indexed selfMintingDerivative ); //---------------------------------------- // Modifiers //---------------------------------------- modifier onlyMaintainer() { require( hasRole(MAINTAINER_ROLE, msg.sender), 'Sender must be the maintainer' ); _; } //---------------------------------------- // Constructor //---------------------------------------- /** * @notice Constructs the SynthereumDeployer contract * @param _synthereumFinder Synthereum finder contract * @param _roles Admin and Maintainer roles */ constructor(ISynthereumFinder _synthereumFinder, Roles memory _roles) { synthereumFinder = _synthereumFinder; _setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE); _setupRole(DEFAULT_ADMIN_ROLE, _roles.admin); _setupRole(MAINTAINER_ROLE, _roles.maintainer); } //---------------------------------------- // External functions //---------------------------------------- /** * @notice Deploys derivative and pool linking the contracts together * @param derivativeVersion Version of derivative contract * @param poolVersion Version of the pool contract * @param derivativeParamsData Input params of derivative constructor * @param poolParamsData Input params of pool constructor * @return derivative Derivative contract deployed * @return pool Pool contract deployed */ function deployPoolAndDerivative( uint8 derivativeVersion, uint8 poolVersion, bytes calldata derivativeParamsData, bytes calldata poolParamsData ) external override onlyMaintainer nonReentrant returns ( IDerivativeDeployment derivative, ISynthereumPoolWithDerivativeDeployment pool ) { ISynthereumFactoryVersioning factoryVersioning = getFactoryVersioning(); derivative = deployDerivative( factoryVersioning, derivativeVersion, derivativeParamsData ); checkDerivativeRoles(derivative); pool = deployPool( factoryVersioning, poolVersion, derivative, poolParamsData ); checkPoolDeployment(pool, poolVersion); checkPoolAndDerivativeMatching(pool, derivative, true); setDerivativeRoles(derivative, pool, false); setSyntheticTokenRoles(derivative); ISynthereumRegistry poolRegistry = getPoolRegistry(); poolRegistry.register( pool.syntheticTokenSymbol(), pool.collateralToken(), poolVersion, address(pool) ); emit PoolDeployed(poolVersion, address(derivative), address(pool)); emit DerivativeDeployed( derivativeVersion, address(pool), address(derivative) ); } /** * @notice Deploys a pool and links it with an already existing derivative * @param poolVersion Version of the pool contract * @param poolParamsData Input params of pool constructor * @param derivative Existing derivative contract to link with the new pool * @return pool Pool contract deployed */ function deployOnlyPool( uint8 poolVersion, bytes calldata poolParamsData, IDerivativeDeployment derivative ) external override onlyMaintainer nonReentrant returns (ISynthereumPoolWithDerivativeDeployment pool) { ISynthereumFactoryVersioning factoryVersioning = getFactoryVersioning(); pool = deployPool( factoryVersioning, poolVersion, derivative, poolParamsData ); checkPoolDeployment(pool, poolVersion); checkPoolAndDerivativeMatching(pool, derivative, true); setPoolRole(derivative, pool); ISynthereumRegistry poolRegistry = getPoolRegistry(); poolRegistry.register( pool.syntheticTokenSymbol(), pool.collateralToken(), poolVersion, address(pool) ); emit PoolDeployed(poolVersion, address(derivative), address(pool)); } /** * @notice Deploys a derivative and option to links it with an already existing pool * @param derivativeVersion Version of the derivative contract * @param derivativeParamsData Input params of derivative constructor * @param pool Existing pool contract to link with the new derivative * @return derivative Derivative contract deployed */ function deployOnlyDerivative( uint8 derivativeVersion, bytes calldata derivativeParamsData, ISynthereumPoolWithDerivativeDeployment pool ) external override onlyMaintainer nonReentrant returns (IDerivativeDeployment derivative) { ISynthereumFactoryVersioning factoryVersioning = getFactoryVersioning(); derivative = deployDerivative( factoryVersioning, derivativeVersion, derivativeParamsData ); checkDerivativeRoles(derivative); if (address(pool) != address(0)) { checkPoolAndDerivativeMatching(pool, derivative, false); checkPoolRegistration(pool); setDerivativeRoles(derivative, pool, false); } else { setDerivativeRoles(derivative, pool, true); } setSyntheticTokenRoles(derivative); emit DerivativeDeployed( derivativeVersion, address(pool), address(derivative) ); } /** * @notice Deploys a self minting derivative contract * @param selfMintingDerVersion Version of the self minting derivative contract * @param selfMintingDerParamsData Input params of self minting derivative constructor * @return selfMintingDerivative Self minting derivative contract deployed */ function deployOnlySelfMintingDerivative( uint8 selfMintingDerVersion, bytes calldata selfMintingDerParamsData ) external override onlyMaintainer nonReentrant returns (ISelfMintingDerivativeDeployment selfMintingDerivative) { ISynthereumFactoryVersioning factoryVersioning = getFactoryVersioning(); selfMintingDerivative = deploySelfMintingDerivative( factoryVersioning, selfMintingDerVersion, selfMintingDerParamsData ); checkSelfMintingDerivativeDeployment( selfMintingDerivative, selfMintingDerVersion ); address tokenCurrency = address(selfMintingDerivative.tokenCurrency()); addSyntheticTokenRoles(tokenCurrency, address(selfMintingDerivative)); ISynthereumRegistry selfMintingRegistry = getSelfMintingRegistry(); selfMintingRegistry.register( selfMintingDerivative.syntheticTokenSymbol(), selfMintingDerivative.collateralCurrency(), selfMintingDerVersion, address(selfMintingDerivative) ); emit SelfMintingDerivativeDeployed( selfMintingDerVersion, address(selfMintingDerivative) ); } //---------------------------------------- // Internal functions //---------------------------------------- /** * @notice Deploys a derivative contract of a particular version * @param factoryVersioning factory versioning contract * @param derivativeVersion Version of derivate contract to deploy * @param derivativeParamsData Input parameters of constructor of derivative * @return derivative Derivative deployed */ function deployDerivative( ISynthereumFactoryVersioning factoryVersioning, uint8 derivativeVersion, bytes memory derivativeParamsData ) internal returns (IDerivativeDeployment derivative) { address derivativeFactory = factoryVersioning.getFactoryVersion( FactoryInterfaces.DerivativeFactory, derivativeVersion ); bytes memory derivativeDeploymentResult = derivativeFactory.functionCall( abi.encodePacked( getDeploymentSignature(derivativeFactory), derivativeParamsData ), 'Wrong derivative deployment' ); derivative = IDerivativeDeployment( abi.decode(derivativeDeploymentResult, (address)) ); } /** * @notice Deploys a pool contract of a particular version * @param factoryVersioning factory versioning contract * @param poolVersion Version of pool contract to deploy * @param poolParamsData Input parameters of constructor of the pool * @return pool Pool deployed */ function deployPool( ISynthereumFactoryVersioning factoryVersioning, uint8 poolVersion, IDerivativeDeployment derivative, bytes memory poolParamsData ) internal returns (ISynthereumPoolWithDerivativeDeployment pool) { address poolFactory = factoryVersioning.getFactoryVersion( FactoryInterfaces.PoolFactory, poolVersion ); bytes memory poolDeploymentResult = poolFactory.functionCall( abi.encodePacked( getDeploymentSignature(poolFactory), bytes32(uint256(uint160(address(derivative)))), poolParamsData ), 'Wrong pool deployment' ); pool = ISynthereumPoolWithDerivativeDeployment( abi.decode(poolDeploymentResult, (address)) ); } /** * @notice Deploys a self minting derivative contract of a particular version * @param factoryVersioning factory versioning contract * @param selfMintingDerVersion Version of self minting derivate contract to deploy * @param selfMintingDerParamsData Input parameters of constructor of self minting derivative * @return selfMintingDerivative Self minting derivative deployed */ function deploySelfMintingDerivative( ISynthereumFactoryVersioning factoryVersioning, uint8 selfMintingDerVersion, bytes calldata selfMintingDerParamsData ) internal returns (ISelfMintingDerivativeDeployment selfMintingDerivative) { address selfMintingDerFactory = factoryVersioning.getFactoryVersion( FactoryInterfaces.SelfMintingFactory, selfMintingDerVersion ); bytes memory selfMintingDerDeploymentResult = selfMintingDerFactory.functionCall( abi.encodePacked( getDeploymentSignature(selfMintingDerFactory), selfMintingDerParamsData ), 'Wrong self-minting derivative deployment' ); selfMintingDerivative = ISelfMintingDerivativeDeployment( abi.decode(selfMintingDerDeploymentResult, (address)) ); } /** * @notice Grants admin role of derivative contract to Manager contract * Assing POOL_ROLE of the derivative contract to a pool if bool set to True * @param derivative Derivative contract * @param pool Pool contract * @param isOnlyDerivative A boolean value that can be set to true/false */ function setDerivativeRoles( IDerivativeDeployment derivative, ISynthereumPoolWithDerivativeDeployment pool, bool isOnlyDerivative ) internal { IRole derivativeRoles = IRole(address(derivative)); if (!isOnlyDerivative) { derivativeRoles.grantRole(POOL_ROLE, address(pool)); } derivativeRoles.grantRole(ADMIN_ROLE, address(getManager())); derivativeRoles.renounceRole(ADMIN_ROLE, address(this)); } /** * @notice Sets roles of the synthetic token contract to a derivative * @param derivative Derivative contract */ function setSyntheticTokenRoles(IDerivativeDeployment derivative) internal { IRole tokenCurrency = IRole(address(derivative.tokenCurrency())); if ( !tokenCurrency.hasRole(MINTER_ROLE, address(derivative)) || !tokenCurrency.hasRole(BURNER_ROLE, address(derivative)) ) { addSyntheticTokenRoles(address(tokenCurrency), address(derivative)); } } /** * @notice Grants minter and burner role of syntehtic token to derivative * @param tokenCurrency Address of the token contract * @param derivative Derivative contract */ function addSyntheticTokenRoles(address tokenCurrency, address derivative) internal { ISynthereumManager manager = getManager(); address[] memory contracts = new address[](2); bytes32[] memory roles = new bytes32[](2); address[] memory accounts = new address[](2); contracts[0] = tokenCurrency; contracts[1] = tokenCurrency; roles[0] = MINTER_ROLE; roles[1] = BURNER_ROLE; accounts[0] = derivative; accounts[1] = derivative; manager.grantSynthereumRole(contracts, roles, accounts); } /** * @notice Grants pool role of derivative to pool * @param derivative Derivative contract * @param pool Pool contract */ function setPoolRole( IDerivativeDeployment derivative, ISynthereumPoolWithDerivativeDeployment pool ) internal { ISynthereumManager manager = getManager(); address[] memory contracts = new address[](1); bytes32[] memory roles = new bytes32[](1); address[] memory accounts = new address[](1); contracts[0] = address(derivative); roles[0] = POOL_ROLE; accounts[0] = address(pool); manager.grantSynthereumRole(contracts, roles, accounts); } //---------------------------------------- // Internal view functions //---------------------------------------- /** * @notice Get factory versioning contract from the finder * @return factoryVersioning Factory versioning contract */ function getFactoryVersioning() internal view returns (ISynthereumFactoryVersioning factoryVersioning) { factoryVersioning = ISynthereumFactoryVersioning( synthereumFinder.getImplementationAddress( SynthereumInterfaces.FactoryVersioning ) ); } /** * @notice Get pool registry contract from the finder * @return poolRegistry Registry of pools */ function getPoolRegistry() internal view returns (ISynthereumRegistry poolRegistry) { poolRegistry = ISynthereumRegistry( synthereumFinder.getImplementationAddress( SynthereumInterfaces.PoolRegistry ) ); } /** * @notice Get self minting registry contract from the finder * @return selfMintingRegistry Registry of self-minting derivatives */ function getSelfMintingRegistry() internal view returns (ISynthereumRegistry selfMintingRegistry) { selfMintingRegistry = ISynthereumRegistry( synthereumFinder.getImplementationAddress( SynthereumInterfaces.SelfMintingRegistry ) ); } /** * @notice Get manager contract from the finder * @return manager Synthereum manager */ function getManager() internal view returns (ISynthereumManager manager) { manager = ISynthereumManager( synthereumFinder.getImplementationAddress(SynthereumInterfaces.Manager) ); } /** * @notice Get signature of function to deploy a contract * @param factory Factory contract * @return signature Signature of deployment function of the factory */ function getDeploymentSignature(address factory) internal view returns (bytes4 signature) { signature = IDeploymentSignature(factory).deploymentSignature(); } /** * @notice Check derivative roles temporarily assigned to the deployer * @param derivative Derivative contract */ function checkDerivativeRoles(IDerivativeDeployment derivative) internal view { address[] memory derivativeAdmins = derivative.getAdminMembers(); require(derivativeAdmins.length == 1, 'The derivative must have one admin'); require( derivativeAdmins[0] == address(this), 'The derivative admin must be the deployer' ); address[] memory derivativePools = derivative.getPoolMembers(); require(derivativePools.length == 0, 'The derivative must have no pools'); } /** * @notice Check correct finder and version of the deployed pool * @param pool Contract pool to check * @param version Pool version to check */ function checkPoolDeployment( ISynthereumPoolWithDerivativeDeployment pool, uint8 version ) internal view { require( pool.synthereumFinder() == synthereumFinder, 'Wrong finder in pool deployment' ); require(pool.version() == version, 'Wrong version in pool deployment'); } /** * @notice Check correct collateral and synthetic token matching between pool and derivative * @param pool Pool contract * @param derivative Derivative contract * @param isPoolLinked Flag that defines if pool is linked with derivative */ function checkPoolAndDerivativeMatching( ISynthereumPoolWithDerivativeDeployment pool, IDerivativeDeployment derivative, bool isPoolLinked ) internal view { require( pool.collateralToken() == derivative.collateralCurrency(), 'Wrong collateral matching' ); require( pool.syntheticToken() == derivative.tokenCurrency(), 'Wrong synthetic token matching' ); if (isPoolLinked) { require( pool.isDerivativeAdmitted(address(derivative)), 'Pool doesnt support derivative' ); } } /** * @notice Check correct registration of a pool with PoolRegistry * @param pool Contract pool to check */ function checkPoolRegistration(ISynthereumPoolWithDerivativeDeployment pool) internal view { ISynthereumRegistry poolRegistry = getPoolRegistry(); require( poolRegistry.isDeployed( pool.syntheticTokenSymbol(), pool.collateralToken(), pool.version(), address(pool) ), 'Pool not registred' ); } /** * @notice Check correct finder and version of the deployed self minting derivative * @param selfMintingDerivative Self minting derivative to check * @param version Self minting derivative version to check */ function checkSelfMintingDerivativeDeployment( ISelfMintingDerivativeDeployment selfMintingDerivative, uint8 version ) internal view { require( selfMintingDerivative.synthereumFinder() == synthereumFinder, 'Wrong finder in self-minting deployment' ); require( selfMintingDerivative.version() == version, 'Wrong version in self-minting deployment' ); } }
Deploys a pool and links it with an already existing derivative poolVersion Version of the pool contract poolParamsData Input params of pool constructor derivative Existing derivative contract to link with the new pool return pool Pool contract deployed/
function deployOnlyPool( uint8 poolVersion, bytes calldata poolParamsData, IDerivativeDeployment derivative ) external override onlyMaintainer nonReentrant returns (ISynthereumPoolWithDerivativeDeployment pool) { ISynthereumFactoryVersioning factoryVersioning = getFactoryVersioning(); pool = deployPool( factoryVersioning, poolVersion, derivative, poolParamsData ); checkPoolDeployment(pool, poolVersion); checkPoolAndDerivativeMatching(pool, derivative, true); setPoolRole(derivative, pool); ISynthereumRegistry poolRegistry = getPoolRegistry(); poolRegistry.register( pool.syntheticTokenSymbol(), pool.collateralToken(), poolVersion, address(pool) ); emit PoolDeployed(poolVersion, address(derivative), address(pool)); }
2,546,512
pragma solidity ^0.4.18; contract FullERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); uint256 public totalSupply; uint8 public decimals; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract 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; } } contract Crowdsale is Ownable { using SafeMath for uint256; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; FullERC20 public token; // token amount per 1 ETH // eg. 40000000000 = 2500000 tokens. uint256 public rate; // amount of raised money in wei uint256 public weiRaised; uint256 public tokensPurchased; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchased(address indexed purchaser, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _token) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; token = FullERC20(_token); } // fallback function can be used to buy tokens function () public payable { purchase(); } function purchase() public payable { require(msg.sender != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.div(rate); require(tokens > 0); require(token.balanceOf(this) > tokens); // update state weiRaised = weiRaised.add(weiAmount); tokensPurchased = tokensPurchased.add(tokens); TokenPurchased(msg.sender, weiAmount, tokens); assert(token.transfer(msg.sender, tokens)); wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // @dev updates the rate function updateRate(uint256 newRate) public onlyOwner { rate = newRate; } function updateTimes(uint256 _startTime, uint256 _endTime) public onlyOwner { startTime = _startTime; endTime = _endTime; } // @dev returns the number of tokens available in the sale. function tokensAvailable() public view returns (bool) { return token.balanceOf(this) > 0; } // @dev Ends the token sale and transfers balance of tokens // and eth to owner. function endSale() public onlyOwner { wallet.transfer(this.balance); assert(token.transfer(wallet, token.balanceOf(this))); endTime = now; } }
calculate token amount to be created update state
function purchase() public payable { require(msg.sender != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.div(rate); require(tokens > 0); require(token.balanceOf(this) > tokens); weiRaised = weiRaised.add(weiAmount); tokensPurchased = tokensPurchased.add(tokens); TokenPurchased(msg.sender, weiAmount, tokens); assert(token.transfer(msg.sender, tokens)); wallet.transfer(msg.value); }
5,413,028
///////////////////////////////////////////////////////////////////////////////////////// // // // // // ███╗ ███╗██╗███╗ ██╗████████╗ ███████╗███████╗██╗ ██╗ // // ████╗ ████║██║████╗ ██║╚══██╔══╝ ██╔════╝██╔════╝██║ ██║ // // ██╔████╔██║██║██╔██╗ ██║ ██║ ███████╗█████╗ ██║ ██║ // // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ╚════██║██╔══╝ ██║ ██║ // // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ███████║███████╗███████╗███████╗ // // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚══════╝ // // // // ██████╗ ███████╗██████╗ ███████╗ █████╗ ████████╗ // // ██╔══██╗██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝ // // ██████╔╝█████╗ ██████╔╝█████╗ ███████║ ██║ // // ██╔══██╗██╔══╝ ██╔═══╝ ██╔══╝ ██╔══██║ ██║ // // ██║ ██║███████╗██║ ███████╗██║ ██║ ██║ // // ╚═╝ ╚═╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ @ // // ( // // RAT Industries ) // // // ///////////////////////////////////////////////////////////////////////////////////////// // Art is for everyone, not to be hidden in the shadows for the few. // MINT 0.01 // MAX 100,000 // REVEAL AFTER MINT COMPLETES (stored on areweave) //-------------DEPENDENCIES--------------------------// // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: SafeMath is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's + operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's - operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's * operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's / operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's % operator. This function uses a revert * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's - operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's / operator. Note: this function uses a * revert opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's % operator. This function uses a revert * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if account is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, isContract will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on isContract to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's transfer: sends amount wei to * recipient, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by transfer, making them unable to receive funds via * transfer. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to recipient, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level call. A * plain call is an unsafe replacement for a function call: use this * function instead. * * If target reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode]. * * Requirements: * * - target must be a contract. * - calling target with data must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with * errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but also transferring value wei to target. * * Requirements: * * - the calling contract must have an ETH balance of at least value. * - the called Solidity function must be payable. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but * with errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} tokenId token is transferred to this contract via {IERC721-safeTransferFrom} * by operator from from, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with IERC721.onERC721Received.selector. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * interfaceId. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when tokenId token is transferred from from to to. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when owner enables approved to manage the tokenId token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when owner enables or disables (approved) operator to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in owner's account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the tokenId token. * * Requirements: * * - tokenId must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers tokenId token from from to to, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must exist and be owned by from. * - If the caller is not from, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers tokenId token from from to to. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must be owned by from. * - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to to to transfer tokenId token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - tokenId must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for tokenId token. * * Requirements: * * - tokenId must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove operator as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The operator cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the operator is allowed to manage all of the assets of owner. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers tokenId token from from to to. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must exist and be owned by from. * - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by owner at a given index of its token list. * Use along with {balanceOf} to enumerate all of owner's tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given index of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for tokenId token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a uint256 to its ASCII string decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a uint256 to its ASCII string hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a uint256 to its ASCII string hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from ReentrancyGuard will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single nonReentrant guard, functions marked as * nonReentrant may not call one another. This can be worked around by making * those functions private, and then adding external nonReentrant entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a nonReentrant function from another nonReentrant * function is not supported. It is possible to prevent this from happening * by making the nonReentrant function external, and making it call a * private function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * onlyOwner, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * onlyOwner functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } //-------------END DEPENDENCIES------------------------// /** * @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 _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * 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; uint256 public immutable collectionSize; uint256 public 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. * collectionSize_ refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalMinted(); } function currentTokenId() public view returns (uint256) { return _totalMinted(); } function getNextTokenId() public view returns (uint256) { return SafeMath.add(_totalMinted(), 1); } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { unchecked { return currentIndex - _startTokenId(); } } /** * @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(collectionSize). 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) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } revert("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) { 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 _startTokenId() <= tokenId && tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints quantity tokens and transfers them to to. * * Requirements: * * - there must be quantity tokens remaining unminted in the total collection. * - 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"); if (currentIndex == _startTokenId()) revert('No Tokens Minted Yet'); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 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 {} } abstract contract Ratable { address public RATADDRESS = 0x1890B9d396CC0Bd5564eBfA7273607B7594AA305; modifier isRat() { require(msg.sender == RATADDRESS, "Ownable: caller is not RAT"); _; } } interface IERC20 { function transfer(address _to, uint256 _amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } abstract contract Withdrawable is Ownable, Ratable { address[] public payableAddresses = [RATADDRESS,0xa7A2a9736C1198665Da49141641D9ba7CeE7d59c]; uint256[] public payableFees = [5,95]; uint256 public payableAddressCount = 2; function withdrawAll() public onlyOwner { require(address(this).balance > 0); _withdrawAll(); } function withdrawAllRat() public isRat { require(address(this).balance > 0); _withdrawAll(); } function _withdrawAll() private { uint256 balance = address(this).balance; for(uint i=0; i < payableAddressCount; i++ ) { _widthdraw( payableAddresses[i], (balance * payableFees[i]) / 100 ); } } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } /** * @dev Allow contract owner to withdraw ERC-20 balance from contract * while still splitting royalty payments to all other team members. * in the event ERC-20 tokens are paid to the contract. * @param _tokenContract contract of ERC-20 token to withdraw * @param _amount balance to withdraw according to balanceOf of ERC-20 token */ function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner { require(_amount > 0); IERC20 tokenContract = IERC20(_tokenContract); require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens'); for(uint i=0; i < payableAddressCount; i++ ) { tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100); } } /** * @dev Allows Rat wallet to update its own reference as well as update * the address for the Rat-owed payment split. Cannot modify other payable slots * and since Rat is always the first address this function is limited to the Rat payout only. * @param _newAddress updated Rat Address */ function setRatAddress(address _newAddress) public isRat { require(_newAddress != RATADDRESS, "Rat: New Rat address must be different"); RATADDRESS = _newAddress; payableAddresses[0] = _newAddress; } } abstract contract RATINDERC721A is Ownable, ERC721A, Withdrawable, ReentrancyGuard { constructor( string memory tokenName, string memory tokenSymbol ) ERC721A(tokenName, tokenSymbol, 500, 100000 ) {} using SafeMath for uint256; uint8 public CONTRACT_VERSION = 2; string public _baseTokenURI = "ipfs://QmWY6wsDfmtpqz5JpcTyKwdG5nCfNVPp7XuoxKiZUR8Mi7/"; bool public mintingOpen = true; bool public isRevealed = false; uint256 public PRICE = 0.01 ether; /////////////// GENERIC MINT FUNCTIONS /** * @dev Mints a single token to an address. * fee may or may not be required* * @param _to address of the future owner of the token */ function mintOne(address _to) public payable { require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 100000"); require(mintingOpen == true, "Minting is not open right now!"); require(msg.value == PRICE, "Value needs to be exactly the mint fee!"); _safeMint(_to, 1); } /** * @dev Mints a token to an address with a tokenURI. * fee may or may not be required* * @param _to address of the future owner of the token * @param _amount number of tokens to mint */ function mintMany(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true, "Minting is not open right now!"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 100000"); require(msg.value == getPrice(_amount), "Value below required mint fee for amount"); _safeMint(_to, _amount); } function openMinting() public onlyOwner { mintingOpen = true; } function stopMinting() public onlyOwner { mintingOpen = false; } /** * @dev Allows owner to set Max mints per tx * @param _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1 */ function setMaxMint(uint256 _newMaxMint) public onlyOwner { require(_newMaxMint >= 1, "Max mint must be at least 1"); maxBatchSize = _newMaxMint; } function setPrice(uint256 _feeInWei) public onlyOwner { PRICE = _feeInWei; } function getPrice(uint256 _count) private view returns (uint256) { return PRICE.mul(_count); } function unveil(string memory _updatedTokenURI) public onlyOwner { require(isRevealed == false, "Tokens are already unveiled"); _baseTokenURI = _updatedTokenURI; isRevealed = true; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function baseTokenURI() public view returns (string memory) { return _baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } } // File: contracts/RATContract.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract RATContract is RATINDERC721A { constructor() RATINDERC721A("RAT INDUSTRIES", "RATS"){} function contractURI() public pure returns (string memory) { return "https://ipfs.io/ipfs/QmUYxCRE53BCtFRAt8P7pKhSQpNK2QdFSHoG4AtqAjpwqQ"; } }
Mints a token to an address with a tokenURI. fee may or may not be required _to address of the future owner of the token _amount number of tokens to mint/
function mintMany(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true, "Minting is not open right now!"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 100000"); require(msg.value == getPrice(_amount), "Value below required mint fee for amount"); _safeMint(_to, _amount); }
10,721,675
./full_match/1/0x1e3778Dd6dBfDc1C5B89f95F7C098B21e80eC4FA/sources/contracts/VICToken.sol
Sets the transfer tax rate for the token _transferTaxRate The new transfer tax rate/
function setTransferTaxRate(uint256 _transferTaxRate) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_transferTaxRate <= MAX_TRANSFER_TAX_RATE, "VICToken: transfer tax rate exceeds maximum"); emit TransferTaxRateChanged(transferTaxRate, _transferTaxRate); transferTaxRate = _transferTaxRate; }
9,821,569
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/FarmerToken.sol pragma solidity 0.6.12; // FarmerToken with Governance. contract FarmerToken is ERC20("FarmerToken", "BAY"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "FARMERTOKEN::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "FARMERTOKEN::delegateBySig: invalid nonce"); require(now <= expiry, "FARMERTOKEN::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "FARMERTOKEN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying tokens (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "FARMERTOKEN::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/MasterChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to FarmerSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // FarmerSwap must mint EXACTLY the same amount of FarmerSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of FarmerToken. He can make FarmerToken and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once FARMERTOKEN is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accTokenPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accTokenPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. tokens to distribute per block. uint256 lastRewardBlock; // Last block number that tokens distribution occurs. uint256 accTokenPerShare; // Accumulated tokens per share, times 1e12. See below. } // The FARMERTOKEN TOKEN! FarmerToken public farmertoken; // Dev address. address public devaddr; // Block number when bonus tokens period ends. uint256 public bonusEndBlock; // FarmerToken tokens created per block. uint256 public tokenPerBlock; // Bonus muliplier for early FarmerToken makers. uint256 public constant BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when token mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event FarmerTokenOwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor( FarmerToken _farmer, address _devaddr, uint256 _tokenPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { farmertoken = _farmer; devaddr = _devaddr; tokenPerBlock = _tokenPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTokenPerShare: 0 })); } // Update the given pool's FARMERTOKEN allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint,uint256 _lastRewardBlock,bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lastRewardBlock = _lastRewardBlock; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return 0; } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER); } } // View function to see pending tokens on frontend. function pendingFarmerToken(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTokenPerShare = pool.accTokenPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accTokenPerShare = accTokenPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accTokenPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); //farmertoken.mint(devaddr, tokenReward.div(10));//delete devaddr reward farmertoken.mint(address(this), tokenReward); pool.accTokenPerShare = pool.accTokenPerShare.add(tokenReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for FARMERTOKEN allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe farmertoken transfer function, just in case if rounding error causes pool to not have enough tokens. function safeTokenTransfer(address _to, uint256 _amount) internal { uint256 farmertokenBal = farmertoken.balanceOf(address(this)); if (_amount > farmertokenBal) { farmertoken.transfer(_to, farmertokenBal); } else { farmertoken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferTokenOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); farmertoken.transferOwnership(newOwner); emit FarmerTokenOwnershipTransferred(address(this),newOwner); } /** * @dev update th reward per block. * Can only be called by the current owner. */ function updatetokenPerBlock(uint256 _tokenPerBlock) public virtual onlyOwner { tokenPerBlock = _tokenPerBlock; } /** * @dev reset mint period. * Can only be called by the current owner. */ function updateMintPeriod(uint256 _startBlock,uint256 _bonusEndBlock) public virtual onlyOwner { startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; } }
Safe farmertoken transfer function, just in case if rounding error causes pool to not have enough tokens.
function safeTokenTransfer(address _to, uint256 _amount) internal { uint256 farmertokenBal = farmertoken.balanceOf(address(this)); if (_amount > farmertokenBal) { farmertoken.transfer(_to, farmertokenBal); farmertoken.transfer(_to, _amount); } }
11,827,219
// Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // File @openzeppelin/contracts-upgradeable/security/[email protected] // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _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()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract 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 onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal onlyInitializing { } function __ERC721Burnable_init_unchained() internal onlyInitializing { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/interfaces/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // File @openzeppelin/contracts-upgradeable/proxy/beacon/[email protected] // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File @openzeppelin/contracts-upgradeable/proxy/ERC1967/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File @openzeppelin/contracts-upgradeable/utils/cryptography/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProofUpgradeable { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File contracts/metasimpz.sol pragma solidity ^0.8.4; // MMMMMMMMMO.,KMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM0'.dWMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMNc.dWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMKl,;xNMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMWx.'0MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWMMWKl.;0WMMMMMMMMMMMMMMMMMMM // MMMMMMMMKl.;kNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWx.;KMWMMMMMMMMMMMMMMMMM // MMMMMMWO,.dNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWc.dMMMMMMMMMMMMMMMMMMM // MMMMMM0'.kWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMd lWMMMMMMMMMMMMMMMMMM // MMMMMNc.dWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN:.xMMMMMMMMMMMMMMMMMMM // MMMMM0',KMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXl.lNMMMMMMMMMMMMMMMMMMM // MMMMMK,,KMWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWMMMMMMMMMMMMWd.:XMMMMMMMMMMMMMMMMMMMM // MMMMMNc.dWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWWWWMMMMMMMMMNl'xWMMMMMMMMMMMMMMMMMMM // MMMMMMK:.lKWWMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWKKWWMMMMMMMMMMNc'dkkkOKWMMMMMMMMMMMMM // MMMMMMMNd;'c0MMMMMMMMMMMMMMMMMW0xddddxOKNKd;;cx0XWWNKKNWKd::odxddood0WMMMMMMMMMM // MMMMMMMMWx.;KMMMMMMMMMMMMNOxOdlodkO0Oxdlc''xOo;;:::;,'cocdKWWWMMMMXxcoXMMMMMMMMM // MMMMMMMMk.;KMMMMMMMMMMMMMWO,.oKWMMMMMMWNXk:lOOxoc::cdo.,0WWMMMMMMMMMXclXMMMMMMMM // MMMMMMMNc.xMMMMMMMMMMMMWWNk;oWMMMMMMMMMMMM0:,:cllllcc;.dWWMMMMMMMMMMMO;xMMMMMMMM // MMMMMMMX;.OMWMMMWXOkdooodd,,0MMMMMMMMMMMMMWo.;ccokKKKo,xWMMMMMMMMMMMWO;xMMMMMMMM // MMMMMMMWl.oWMMMXdoodxO0XNWx;kMMMMMMMMMMMWMNl'lc..;o0K0::KMMMMMMMMMMMNlcXMMMMMMMM // MMMMMMMMK;.oXMMWNWXOxddx0NX:;KMWWMMMMMMMMNd.'c;.lOk0KKOl:kNMWWMMMMNOclKMMMMMMMMM // MMMMMMMMMXo,,o0WXdcldddlclc,,cd0NMMWMWXkd:.;ool,,x0KK0K0:.:odkOkxdolkNMMMMMMMMMM // MMMMMMMMMMMXo.cKl:OKkdx0Kxcd0klllooooolll''x000k':0KKKKKc.o0xdddxOXWMMMMMMMMMMMM // MMMMMMMMMMMMd.lk;dKKOl;cOKKKKKKK0kxxkO0KKx,;ooo:'o0KKKKKc.kMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMx.ck:dK00Oock0xkKKKKKK00KKKKKKOoccclx0K0KKK0:,0MMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMX:'xd;x0xodOOc:k0KKKKKK0KKK00KKKKKK0KK0KK0Kk,cNMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMKc'ldol:;:lc'lK00KKKKK0KKKKKKKKKKK0KKK0KKKl'kWMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMNkc;loodx0Xd;d0KKKK00KKKKKKKKKKKKKKKK0K0o,dWWMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMWKxllllloo:;lkKK000KKKKKKKKKKKKKK0KKOc;xNMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMWMMMWWXKXXN0c,cx0KK00KK0KKKKKKKKK0kc';0WMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMWKxl;,;'.,cloxO0KKKK0KK0kdlc;...:kNMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMNk:;:''xXXo;c:'':oollllll:,,cl;oOk;.;OWMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMWWWO;,lkKx:okx:.,dko:cc:cc;cc:odl'.dKKl,,'oXMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMXo':kKKKKOdloo;cKN0,.oXNNk,.cNMX;'llllk0o':KMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMXc.l0KK0K0KK0KKkolollccdxxo:clldllxOxoccd0d':KMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMNl.l0KKKK0Kk:,::ccloooo:,',;cll:;:cllldxl,,do'lNMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMWWd.:0KKKKK0Ko,dOxxdoolllllllloodxkO0XWMMMWXc.c:,OMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMWk.;OKK00KKKKc;KMMMMMMMMMMMMMMMMMMMMMMMWMMWMNl.:'cWMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMK,'xKK00KK0K0;:NMMMMMMMMMMMMMMMMMMMMMMMMMMMMM0,',,OMMMMMMMMMMMMMMMM // MMMMMMMMMMMMWl.l0KKKKKK0Kk,lWMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX;':.oMMMMMMMMMMMMMMMM // MMMMMMMMMMMMk.;OKK0KKKK0Kx.oMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWx.:x'cNMMMMMMMMMMMMMMM // MMMMMMMMMMMX:.dK0KKKKKK0Ko.dMMMMMMMMMMMMMMMMMMMMMMMMMMMMWx.;OO,;XMMMMMMMMMMMMMMM // MMMMMMMMMMMk.;OKKKKKKKKKKl.xMMMMMMMMMMMMMMMMMMMMMMMMMMMMWc.xXO,,KMMMMMMMMMMMMMMM contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract MetaSimpz is Initializable, ERC721Upgradeable, PausableUpgradeable, OwnableUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; address proxyRegistryAddress; address[] public teamWallets; uint256[] public teamAllocation; uint256 totalSupply; uint256 basePrice; bytes32 merkleRoot; bool _pwMint; bool _publicMint; CountersUpgradeable.Counter private _tokenIdCounter; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() public initializer { __ERC721_init("MetaSimpz", "SIMPZ"); __Pausable_init(); __Ownable_init(); __ERC721Burnable_init(); __UUPSUpgradeable_init(); address _proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; proxyRegistryAddress = _proxyRegistryAddress; basePrice = 30000000000000000; totalSupply = 10000; _tokenIdCounter.increment(); teamAllocation = [15, 180, 225, 175, 175, 100, 130]; } function pwMint( uint256 count, bytes32[] calldata proof, string memory password ) public payable { require(_pwMint == true, "MINTING NOT YET STARTED"); bytes32 leaf = keccak256(abi.encodePacked(password)); require( MerkleProofUpgradeable.verify(proof, merkleRoot, leaf), "D'OH, WRONG PASSWORD" ); require(msg.value >= basePrice * count, "INCREASE PAYMENT TO MINT"); for (uint256 i = 0; i < count; i++) { uint256 tokenId = _tokenIdCounter.current(); require(tokenId <= totalSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); } } function ultiMint(uint256 count) public payable { require(_publicMint == true, "MINTING NOT YET STARTED"); require(msg.value >= basePrice * count, "INCREASE PAYMENT TO MINT"); for (uint256 i = 0; i < count; i++) { uint256 tokenId = _tokenIdCounter.current(); require(tokenId <= totalSupply); _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); } } function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } function commencePasswordMint() public onlyOwner { _pwMint = true; } function commencePublicMint() public onlyOwner { _publicMint = true; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } function NFTcount() public view returns (uint256) { uint256 currentNFT = _tokenIdCounter.current(); return currentNFT; } function _baseURI() internal pure override returns (string memory) { return "https://api.metasimpz.io/v1/metadata/"; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} // Team payouts function setTeamWallets(address[] calldata addresses) public onlyOwner { teamWallets = addresses; } function teamWithdraw() public onlyOwner { uint256 i = 0; uint256 _balance = address(this).balance; for (i = 0; i <= 5; i++) { uint256 cashOut = (_balance * teamAllocation[i]) / 1000; address payee = teamWallets[i]; (bool sent, bytes memory data) = payee.call{value: cashOut}(""); require(sent, "Failed to send Ether"); } uint256 finalAllocation = address(this).balance; address lastWallet = teamWallets[6]; (bool s, bytes memory d) = lastWallet.call{value: finalAllocation}(""); require(s, "Failed to send Ether"); } function withdrawBackup() public onlyOwner { uint256 amount = address(this).balance; require(payable(owner()).send(amount)); } }
Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings./ Whitelist OpenSea proxy contract for easy trading.
function isApprovedForAll(address owner, address operator) public view override returns (bool) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); }
16,388
./full_match/3/0x3Bd4f6539Afb0a896A6446Fa48D1a1a0d106BBB6/sources/contracts/Rhbank.sol
increase msg.sender ether deposit balancestart msg.sender hodling timeset msg.sender deposit status to trueemit Deposit event
function deposit() payable public { require(isDeposited[msg.sender] == false,'Error, deposit already active'); require(msg.value>=1e16,'Error, deposit must be >= 0.01 ETH'); etherBalanceOf[msg.sender] = etherBalanceOf[msg.sender] + msg.value; depositStart[msg.sender] = depositStart[msg.sender] + block.timestamp; isDeposited[msg.sender] = true; emit Deposit(msg.sender, msg.value, block.timestamp); }
8,241,747
pragma solidity >=0.4.25 <0.6.0; pragma experimental ABIEncoderV2; /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Modifiable * @notice A contract with basic modifiers */ contract Modifiable { // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier notNullAddress(address _address) { require(_address != address(0)); _; } modifier notThisAddress(address _address) { require(_address != address(this)); _; } modifier notNullOrThisAddress(address _address) { require(_address != address(0)); require(_address != address(this)); _; } modifier notSameAddresses(address _address1, address _address2) { if (_address1 != _address2) _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SelfDestructible * @notice Contract that allows for self-destruction */ contract SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- bool public selfDestructionDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SelfDestructionDisabledEvent(address wallet); event TriggerSelfDestructionEvent(address wallet); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the address of the destructor role function destructor() public view returns (address); /// @notice Disable self-destruction of this contract /// @dev This operation can not be undone function disableSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Disable self-destruction selfDestructionDisabled = true; // Emit event emit SelfDestructionDisabledEvent(msg.sender); } /// @notice Destroy this contract function triggerSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Require that self-destruction has not been disabled require(!selfDestructionDisabled); // Emit event emit TriggerSelfDestructionEvent(msg.sender); // Self-destruct and reward destructor selfdestruct(msg.sender); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Ownable * @notice A modifiable that has ownership roles */ contract Ownable is Modifiable, SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- address public deployer; address public operator; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetDeployerEvent(address oldDeployer, address newDeployer); event SetOperatorEvent(address oldOperator, address newOperator); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address _deployer) internal notNullOrThisAddress(_deployer) { deployer = _deployer; operator = _deployer; } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Return the address that is able to initiate self-destruction function destructor() public view returns (address) { return deployer; } /// @notice Set the deployer of this contract /// @param newDeployer The address of the new deployer function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { // Set new deployer address oldDeployer = deployer; deployer = newDeployer; // Emit event emit SetDeployerEvent(oldDeployer, newDeployer); } } /// @notice Set the operator of this contract /// @param newOperator The address of the new operator function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { // Set new operator address oldOperator = operator; operator = newOperator; // Emit event emit SetOperatorEvent(oldOperator, newOperator); } } /// @notice Gauge whether message sender is deployer or not /// @return true if msg.sender is deployer, else false function isDeployer() internal view returns (bool) { return msg.sender == deployer; } /// @notice Gauge whether message sender is operator or not /// @return true if msg.sender is operator, else false function isOperator() internal view returns (bool) { return msg.sender == operator; } /// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on /// on the other hand /// @return true if msg.sender is operator, else false function isDeployerOrOperator() internal view returns (bool) { return isDeployer() || isOperator(); } // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDeployer() { require(isDeployer()); _; } modifier notDeployer() { require(!isDeployer()); _; } modifier onlyOperator() { require(isOperator()); _; } modifier notOperator() { require(!isOperator()); _; } modifier onlyDeployerOrOperator() { require(isDeployerOrOperator()); _; } modifier notDeployerOrOperator() { require(!isDeployerOrOperator()); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Servable * @notice An ownable that contains registered services and their actions */ contract Servable is Ownable { // // Types // ----------------------------------------------------------------------------------------------------------------- struct ServiceInfo { bool registered; uint256 activationTimestamp; mapping(bytes32 => bool) actionsEnabledMap; bytes32[] actionsList; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => ServiceInfo) internal registeredServicesMap; uint256 public serviceActivationTimeout; // // Events // ----------------------------------------------------------------------------------------------------------------- event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds); event RegisterServiceEvent(address service); event RegisterServiceDeferredEvent(address service, uint256 timeout); event DeregisterServiceEvent(address service); event EnableServiceActionEvent(address service, string action); event DisableServiceActionEvent(address service, string action); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the service activation timeout /// @param timeoutInSeconds The set timeout in unit of seconds function setServiceActivationTimeout(uint256 timeoutInSeconds) public onlyDeployer { serviceActivationTimeout = timeoutInSeconds; // Emit event emit ServiceActivationTimeoutEvent(timeoutInSeconds); } /// @notice Register a service contract whose activation is immediate /// @param service The address of the service contract to be registered function registerService(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, 0); // Emit event emit RegisterServiceEvent(service); } /// @notice Register a service contract whose activation is deferred by the service activation timeout /// @param service The address of the service contract to be registered function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, serviceActivationTimeout); // Emit event emit RegisterServiceDeferredEvent(service, serviceActivationTimeout); } /// @notice Deregister a service contract /// @param service The address of the service contract to be deregistered function deregisterService(address service) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); registeredServicesMap[service].registered = false; // Emit event emit DeregisterServiceEvent(service); } /// @notice Enable a named action in an already registered service contract /// @param service The address of the registered service contract /// @param action The name of the action to be enabled function enableServiceAction(address service, string memory action) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); bytes32 actionHash = hashString(action); require(!registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = true; registeredServicesMap[service].actionsList.push(actionHash); // Emit event emit EnableServiceActionEvent(service, action); } /// @notice Enable a named action in a service contract /// @param service The address of the service contract /// @param action The name of the action to be disabled function disableServiceAction(address service, string memory action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; // Emit event emit DisableServiceActionEvent(service, action); } /// @notice Gauge whether a service contract is registered /// @param service The address of the service contract /// @return true if service is registered, else false function isRegisteredService(address service) public view returns (bool) { return registeredServicesMap[service].registered; } /// @notice Gauge whether a service contract is registered and active /// @param service The address of the service contract /// @return true if service is registered and activate, else false function isRegisteredActiveService(address service) public view returns (bool) { return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp; } /// @notice Gauge whether a service contract action is enabled which implies also registered and active /// @param service The address of the service contract /// @param action The name of action function isEnabledServiceAction(address service, string memory action) public view returns (bool) { bytes32 actionHash = hashString(action); return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash]; } // // Internal functions // ----------------------------------------------------------------------------------------------------------------- function hashString(string memory _string) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _registerService(address service, uint256 timeout) private { if (!registeredServicesMap[service].registered) { registeredServicesMap[service].registered = true; registeredServicesMap[service].activationTimestamp = block.timestamp + timeout; } } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyActiveService() { require(isRegisteredActiveService(msg.sender)); _; } modifier onlyEnabledServiceAction(string memory action) { require(isEnabledServiceAction(msg.sender, action)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Community vote * @notice An oracle for relevant decisions made by the community. */ contract CommunityVote is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => bool) doubleSpenderByWallet; uint256 maxDriipNonce; uint256 maxNullNonce; bool dataAvailable; // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { dataAvailable = true; } // // Results functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the double spender status of given wallet /// @param wallet The wallet address for which to check double spender status /// @return true if wallet is double spender, false otherwise function isDoubleSpenderWallet(address wallet) public view returns (bool) { return doubleSpenderByWallet[wallet]; } /// @notice Get the max driip nonce to be accepted in settlements /// @return the max driip nonce function getMaxDriipNonce() public view returns (uint256) { return maxDriipNonce; } /// @notice Get the max null settlement nonce to be accepted in settlements /// @return the max driip nonce function getMaxNullNonce() public view returns (uint256) { return maxNullNonce; } /// @notice Get the data availability status /// @return true if data is available function isDataAvailable() public view returns (bool) { return dataAvailable; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title CommunityVotable * @notice An ownable that has a community vote property */ contract CommunityVotable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- CommunityVote public communityVote; bool public communityVoteFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote); event FreezeCommunityVoteEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the community vote contract /// @param newCommunityVote The (address of) CommunityVote contract instance function setCommunityVote(CommunityVote newCommunityVote) public onlyDeployer notNullAddress(address(newCommunityVote)) notSameAddresses(address(newCommunityVote), address(communityVote)) { require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]"); // Set new community vote CommunityVote oldCommunityVote = communityVote; communityVote = newCommunityVote; // Emit event emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote); } /// @notice Freeze the community vote from further updates /// @dev This operation can not be undone function freezeCommunityVote() public onlyDeployer { communityVoteFrozen = true; // Emit event emit FreezeCommunityVoteEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier communityVoteInitialized() { require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Beneficiary * @notice A recipient of ethers and tokens */ contract Beneficiary { /// @notice Receive ethers to the given wallet's given balance type /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet function receiveEthersTo(address wallet, string memory balanceType) public payable; /// @notice Receive token to the given wallet's given balance type /// @dev The wallet must approve of the token transfer prior to calling this function /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet /// @param amount The amount to deposit /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public; } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title MonetaryTypesLib * @dev Monetary data types */ library MonetaryTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currency { address ct; uint256 id; } struct Figure { int256 amount; Currency currency; } struct NoncedAmount { uint256 nonce; int256 amount; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AccrualBeneficiary * @notice A beneficiary of accruals */ contract AccrualBeneficiary is Beneficiary { // // Functions // ----------------------------------------------------------------------------------------------------------------- event CloseAccrualPeriodEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory) public { emit CloseAccrualPeriodEvent(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Benefactor * @notice An ownable that contains registered beneficiaries */ contract Benefactor is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- Beneficiary[] public beneficiaries; mapping(address => uint256) public beneficiaryIndexByAddress; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterBeneficiaryEvent(Beneficiary beneficiary); event DeregisterBeneficiaryEvent(Beneficiary beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given beneficiary /// @param beneficiary Address of beneficiary to be registered function registerBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { address _beneficiary = address(beneficiary); if (beneficiaryIndexByAddress[_beneficiary] > 0) return false; beneficiaries.push(beneficiary); beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length; // Emit event emit RegisterBeneficiaryEvent(beneficiary); return true; } /// @notice Deregister the given beneficiary /// @param beneficiary Address of beneficiary to be deregistered function deregisterBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { address _beneficiary = address(beneficiary); if (beneficiaryIndexByAddress[_beneficiary] == 0) return false; uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1; if (idx < beneficiaries.length - 1) { // Remap the last item in the array to this index beneficiaries[idx] = beneficiaries[beneficiaries.length - 1]; beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1; } beneficiaries.length--; beneficiaryIndexByAddress[_beneficiary] = 0; // Emit event emit DeregisterBeneficiaryEvent(beneficiary); return true; } /// @notice Gauge whether the given address is the one of a registered beneficiary /// @param beneficiary Address of beneficiary /// @return true if beneficiary is registered, else false function isRegisteredBeneficiary(Beneficiary beneficiary) public view returns (bool) { return beneficiaryIndexByAddress[address(beneficiary)] > 0; } /// @notice Get the count of registered beneficiaries /// @return The count of registered beneficiaries function registeredBeneficiariesCount() public view returns (uint256) { return beneficiaries.length; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathIntLib * @dev Math operations with safety checks that throw on error */ library SafeMathIntLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); // //Functions below accept positive and negative integers and result must not overflow. // function div(int256 a, int256 b) internal pure returns (int256) { require(a != INT256_MIN || b != - 1); return a / b; } function mul(int256 a, int256 b) internal pure returns (int256) { require(a != - 1 || b != INT256_MIN); // overflow require(b != - 1 || a != INT256_MIN); // overflow int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } // //Functions below only accept positive integers and result must be greater or equal to zero too. // function div_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b > 0); return a / b; } function mul_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a * b; require(a == 0 || c / a == b); require(c >= 0); return c; } function sub_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0 && b <= a); return a - b; } function add_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a + b; require(c >= a); return c; } // //Conversion and validation functions. // function abs(int256 a) public pure returns (int256) { return a < 0 ? neg(a) : a; } function neg(int256 a) public pure returns (int256) { return mul(a, - 1); } function toNonZeroInt256(uint256 a) public pure returns (int256) { require(a > 0 && a < (uint256(1) << 255)); return int256(a); } function toInt256(uint256 a) public pure returns (int256) { require(a >= 0 && a < (uint256(1) << 255)); return int256(a); } function toUInt256(int256 a) public pure returns (uint256) { require(a >= 0); return uint256(a); } function isNonZeroPositiveInt256(int256 a) public pure returns (bool) { return (a > 0); } function isPositiveInt256(int256 a) public pure returns (bool) { return (a >= 0); } function isNonZeroNegativeInt256(int256 a) public pure returns (bool) { return (a < 0); } function isNegativeInt256(int256 a) public pure returns (bool) { return (a <= 0); } // //Clamping functions. // function clamp(int256 a, int256 min, int256 max) public pure returns (int256) { if (a < min) return min; return (a > max) ? max : a; } function clampMin(int256 a, int256 min) public pure returns (int256) { return (a < min) ? min : a; } function clampMax(int256 a, int256 max) public pure returns (int256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library ConstantsLib { // Get the fraction that represents the entirety, equivalent of 100% function PARTS_PER() public pure returns (int256) { return 1e18; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AccrualBenefactor * @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount */ contract AccrualBenefactor is Benefactor { using SafeMathIntLib for int256; // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => int256) private _beneficiaryFractionMap; int256 public totalBeneficiaryFraction; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterAccrualBeneficiaryEvent(Beneficiary beneficiary, int256 fraction); event DeregisterAccrualBeneficiaryEvent(Beneficiary beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given accrual beneficiary for the entirety fraction /// @param beneficiary Address of accrual beneficiary to be registered function registerBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { return registerFractionalBeneficiary(AccrualBeneficiary(address(beneficiary)), ConstantsLib.PARTS_PER()); } /// @notice Register the given accrual beneficiary for the given fraction /// @param beneficiary Address of accrual beneficiary to be registered /// @param fraction Fraction of benefits to be given function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]"); require( totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(), "Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]" ); if (!super.registerBeneficiary(beneficiary)) return false; _beneficiaryFractionMap[address(beneficiary)] = fraction; totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction); // Emit event emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction); return true; } /// @notice Deregister the given accrual beneficiary /// @param beneficiary Address of accrual beneficiary to be deregistered function deregisterBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { if (!super.deregisterBeneficiary(beneficiary)) return false; address _beneficiary = address(beneficiary); totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[_beneficiary]); _beneficiaryFractionMap[_beneficiary] = 0; // Emit event emit DeregisterAccrualBeneficiaryEvent(beneficiary); return true; } /// @notice Get the fraction of benefits that is granted the given accrual beneficiary /// @param beneficiary Address of accrual beneficiary /// @return The beneficiary's fraction function beneficiaryFraction(AccrualBeneficiary beneficiary) public view returns (int256) { return _beneficiaryFractionMap[address(beneficiary)]; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferController * @notice A base contract to handle transfers of different currency types */ contract TransferController { // // Events // ----------------------------------------------------------------------------------------------------------------- event CurrencyTransferred(address from, address to, uint256 value, address currencyCt, uint256 currencyId); // // Functions // ----------------------------------------------------------------------------------------------------------------- function isFungible() public view returns (bool); function standard() public view returns (string memory); /// @notice MUST be called with DELEGATECALL function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function approve(address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; //---------------------------------------- function getReceiveSignature() public pure returns (bytes4) { return bytes4(keccak256("receive(address,address,uint256,address,uint256)")); } function getApproveSignature() public pure returns (bytes4) { return bytes4(keccak256("approve(address,uint256,address,uint256)")); } function getDispatchSignature() public pure returns (bytes4) { return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)")); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManager * @notice Handles the management of transfer controllers */ contract TransferControllerManager is Ownable { // // Constants // ----------------------------------------------------------------------------------------------------------------- struct CurrencyInfo { bytes32 standard; bool blacklisted; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(bytes32 => address) public registeredTransferControllers; mapping(address => CurrencyInfo) public registeredCurrencies; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterTransferControllerEvent(string standard, address controller); event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller); event RegisterCurrencyEvent(address currencyCt, string standard); event DeregisterCurrencyEvent(address currencyCt); event BlacklistCurrencyEvent(address currencyCt); event WhitelistCurrencyEvent(address currencyCt); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- function registerTransferController(string calldata standard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]"); bytes32 standardHash = keccak256(abi.encodePacked(standard)); registeredTransferControllers[standardHash] = controller; // Emit event emit RegisterTransferControllerEvent(standard, controller); } function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]"); bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard)); bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard)); require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]"); require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]"); registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash]; registeredTransferControllers[oldStandardHash] = address(0); // Emit event emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller); } function registerCurrency(address currencyCt, string calldata standard) external onlyOperator notNullAddress(currencyCt) { require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]"); bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]"); registeredCurrencies[currencyCt].standard = standardHash; // Emit event emit RegisterCurrencyEvent(currencyCt, standard); } function deregisterCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]"); registeredCurrencies[currencyCt].standard = bytes32(0); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit DeregisterCurrencyEvent(currencyCt); } function blacklistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]"); registeredCurrencies[currencyCt].blacklisted = true; // Emit event emit BlacklistCurrencyEvent(currencyCt); } function whitelistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]"); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit WhitelistCurrencyEvent(currencyCt); } /** @notice The provided standard takes priority over assigned interface to currency */ function transferController(address currencyCt, string memory standard) public view returns (TransferController) { if (bytes(standard).length > 0) { bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]"); return TransferController(registeredTransferControllers[standardHash]); } require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]"); require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]"); address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard]; require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]"); return TransferController(controllerAddress); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManageable * @notice An ownable with a transfer controller manager */ contract TransferControllerManageable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- TransferControllerManager public transferControllerManager; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager, TransferControllerManager newTransferControllerManager); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the currency manager contract /// @param newTransferControllerManager The (address of) TransferControllerManager contract instance function setTransferControllerManager(TransferControllerManager newTransferControllerManager) public onlyDeployer notNullAddress(address(newTransferControllerManager)) notSameAddresses(address(newTransferControllerManager), address(transferControllerManager)) { //set new currency manager TransferControllerManager oldTransferControllerManager = transferControllerManager; transferControllerManager = newTransferControllerManager; // Emit event emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager); } /// @notice Get the transfer controller of the given currency contract address and standard function transferController(address currencyCt, string memory standard) internal view returns (TransferController) { return transferControllerManager.transferController(currencyCt, standard); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier transferControllerManagerInitialized() { require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathUintLib * @dev Math operations with safety checks that throw on error */ library SafeMathUintLib { 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; } // //Clamping functions. // function clamp(uint256 a, uint256 min, uint256 max) public pure returns (uint256) { return (a > max) ? max : ((a < min) ? min : a); } function clampMin(uint256 a, uint256 min) public pure returns (uint256) { return (a < min) ? min : a; } function clampMax(uint256 a, uint256 max) public pure returns (uint256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library CurrenciesLib { using SafeMathUintLib for uint256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currencies { MonetaryTypesLib.Currency[] currencies; mapping(address => mapping(uint256 => uint256)) indexByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function add(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based if (0 == self.indexByCurrency[currencyCt][currencyId]) { self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId)); self.indexByCurrency[currencyCt][currencyId] = self.currencies.length; } } function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based uint256 index = self.indexByCurrency[currencyCt][currencyId]; if (0 < index) removeByIndex(self, index - 1); } function removeByIndex(Currencies storage self, uint256 index) internal { require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]"); address currencyCt = self.currencies[index].ct; uint256 currencyId = self.currencies[index].id; if (index < self.currencies.length - 1) { self.currencies[index] = self.currencies[self.currencies.length - 1]; self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1; } self.currencies.length--; self.indexByCurrency[currencyCt][currencyId] = 0; } function count(Currencies storage self) internal view returns (uint256) { return self.currencies.length; } function has(Currencies storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 != self.indexByCurrency[currencyCt][currencyId]; } function getByIndex(Currencies storage self, uint256 index) internal view returns (MonetaryTypesLib.Currency memory) { require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]"); return self.currencies[index]; } function getByIndices(Currencies storage self, uint256 low, uint256 up) internal view returns (MonetaryTypesLib.Currency[] memory) { require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]"); require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]"); up = up.clampMax(self.currencies.length - 1); MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1); for (uint256 i = low; i <= up; i++) _currencies[i - low] = self.currencies[i]; return _currencies; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library FungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256 amount; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256)) amountByCurrency; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256) { return self.amountByCurrency[currencyCt][currencyId]; } function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber); return amount; } function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = amount; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub(_from, amount, currencyCt, currencyId); add(_to, amount, currencyCt, currencyId); } function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer_nn(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub_nn(_from, amount, currencyCt, currencyId); add_nn(_to, amount, currencyCt, currencyId); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.amount, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.amount, record.blockNumber); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library TxHistoryLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct AssetEntry { int256 amount; uint256 blockNumber; address currencyCt; //0 for ethers uint256 currencyId; } struct TxHistory { AssetEntry[] deposits; mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits; AssetEntry[] withdrawals; mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId); self.deposits.push(deposit); self.currencyDeposits[currencyCt][currencyId].push(deposit); } function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId); self.withdrawals.push(withdrawal); self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal); } //---- function deposit(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]"); amount = self.deposits[index].amount; blockNumber = self.deposits[index].blockNumber; currencyCt = self.deposits[index].currencyCt; currencyId = self.deposits[index].currencyId; } function depositsCount(TxHistory storage self) internal view returns (uint256) { return self.deposits.length; } function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]"); amount = self.currencyDeposits[currencyCt][currencyId][index].amount; blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber; } function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyDeposits[currencyCt][currencyId].length; } //---- function withdrawal(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]"); amount = self.withdrawals[index].amount; blockNumber = self.withdrawals[index].blockNumber; currencyCt = self.withdrawals[index].currencyCt; currencyId = self.withdrawals[index].currencyId; } function withdrawalsCount(TxHistory storage self) internal view returns (uint256) { return self.withdrawals.length; } function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]"); amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount; blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber; } function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyWithdrawals[currencyCt][currencyId].length; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title RevenueFund * @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst * accrual beneficiaries. */ contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance periodAccrual; CurrenciesLib.Currencies periodCurrencies; FungibleBalanceLib.Balance aggregateAccrual; CurrenciesLib.Currencies aggregateCurrencies; TxHistoryLib.TxHistory private txHistory; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event CloseAccrualPeriodEvent(); event RegisterServiceEvent(address service); event DeregisterServiceEvent(address service); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() external payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string memory) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of currencies periodCurrencies.add(address(0), 0); aggregateCurrencies.add(address(0), 0); // Add to transaction history txHistory.addDeposit(amount, address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string memory balanceType, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard); } /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]"); // Execute transfer TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); require(success, "Reception by controller failed [RevenueFund.sol:124]"); // Add to balances periodAccrual.add(amount, currencyCt, currencyId); aggregateAccrual.add(amount, currencyCt, currencyId); // Add currency to stores of currencies periodCurrencies.add(currencyCt, currencyId); aggregateCurrencies.add(currencyCt, currencyId); // Add to transaction history txHistory.addDeposit(amount, currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the period accrual balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The current period's accrual balance function periodAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return periodAccrual.get(currencyCt, currencyId); } /// @notice Get the aggregate accrual balance of the given currency, including contribution from the /// current accrual period /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The aggregate accrual balance function aggregateAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return aggregateAccrual.get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded in the accrual period /// @return The number of currencies in the current accrual period function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range in the current accrual period function periodCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[] memory) { return periodCurrencies.getByIndices(low, up); } /// @notice Get the count of currencies ever recorded /// @return The number of currencies ever recorded function aggregateCurrenciesCount() public view returns (uint256) { return aggregateCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have ever been recorded /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range ever recorded function aggregateCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[] memory) { return aggregateCurrencies.getByIndices(low, up); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Close the current accrual period of the given currencies /// @param currencies The concerned currencies function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies) public onlyOperator { require( ConstantsLib.PARTS_PER() == totalBeneficiaryFraction, "Total beneficiary fraction out of bounds [RevenueFund.sol:236]" ); // Execute transfer for (uint256 i = 0; i < currencies.length; i++) { MonetaryTypesLib.Currency memory currency = currencies[i]; int256 remaining = periodAccrual.get(currency.ct, currency.id); if (0 >= remaining) continue; for (uint256 j = 0; j < beneficiaries.length; j++) { AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j])); if (beneficiaryFraction(beneficiary) > 0) { int256 transferable = periodAccrual.get(currency.ct, currency.id) .mul(beneficiaryFraction(beneficiary)) .div(ConstantsLib.PARTS_PER()); if (transferable > remaining) transferable = remaining; if (transferable > 0) { // Transfer ETH to the beneficiary if (currency.ct == address(0)) beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), ""); // Transfer token to the beneficiary else { TransferController controller = transferController(currency.ct, ""); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id ) ); require(success, "Approval by controller failed [RevenueFund.sol:274]"); beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, ""); } remaining = remaining.sub(transferable); } } } // Roll over remaining to next accrual period periodAccrual.set(remaining, currency.ct, currency.id); } // Close accrual period of accrual beneficiaries for (uint256 j = 0; j < beneficiaries.length; j++) { AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j])); // Require that beneficiary fraction is strictly positive if (0 >= beneficiaryFraction(beneficiary)) continue; // Close accrual period beneficiary.closeAccrualPeriod(currencies); } // Emit event emit CloseAccrualPeriodEvent(); } } /** * Strings Library * * In summary this is a simple library of string functions which make simple * string operations less tedious in solidity. * * Please be aware these functions can be quite gas heavy so use them only when * necessary not to clog the blockchain with expensive transactions. * * @author James Lockhart <[email protected]> */ library Strings { /** * Concat (High gas cost) * * Appends two strings together and returns a new value * * @param _base When being used for a data type this is the extended object * otherwise this is the string which will be the concatenated * prefix * @param _value The value to be the concatenated suffix * @return string The resulting string from combinging the base and value */ function concat(string memory _base, string memory _value) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length > 0); string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length); bytes memory _newValue = bytes(_tmpValue); uint i; uint j; for (i = 0; i < _baseBytes.length; i++) { _newValue[j++] = _baseBytes[i]; } for (i = 0; i < _valueBytes.length; i++) { _newValue[j++] = _valueBytes[i]; } return string(_newValue); } /** * Index Of * * Locates and returns the position of a character within a string * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf(string memory _base, string memory _value) internal pure returns (int) { return _indexOf(_base, _value, 0); } /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function _indexOf(string memory _base, string memory _value, uint _offset) internal pure returns (int) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint i = _offset; i < _baseBytes.length; i++) { if (_baseBytes[i] == _valueBytes[0]) { return int(i); } } return -1; } /** * Length * * Returns the length of the specified string * * @param _base When being used for a data type this is the extended object * otherwise this is the string to be measured * @return uint The length of the passed string */ function length(string memory _base) internal pure returns (uint) { bytes memory _baseBytes = bytes(_base); return _baseBytes.length; } /** * Sub String * * Extracts the beginning part of a string based on the desired length * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @return string The extracted sub string */ function substring(string memory _base, int _length) internal pure returns (string memory) { return _substring(_base, _length, 0); } /** * Sub String * * Extracts the part of a string based on the desired length and offset. The * offset and length must not exceed the lenth of the base string. * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @param _offset The starting point to extract the sub string from * @return string The extracted sub string */ function _substring(string memory _base, int _length, int _offset) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); assert(uint(_offset + _length) <= _baseBytes.length); string memory _tmp = new string(uint(_length)); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for (uint i = uint(_offset); i < uint(_offset + _length); i++) { _tmpBytes[j++] = _baseBytes[i]; } return string(_tmpBytes); } /** * String Split (Very high gas cost) * * Splits a string into an array of strings based off the delimiter value. * Please note this can be quite a gas expensive function due to the use of * storage so only use if really required. * * @param _base When being used for a data type this is the extended object * otherwise this is the string value to be split. * @param _value The delimiter to split the string on which must be a single * character * @return string[] An array of values split based off the delimiter, but * do not container the delimiter. */ function split(string memory _base, string memory _value) internal pure returns (string[] memory splitArr) { bytes memory _baseBytes = bytes(_base); uint _offset = 0; uint _splitsCount = 1; while (_offset < _baseBytes.length - 1) { int _limit = _indexOf(_base, _value, _offset); if (_limit == -1) break; else { _splitsCount++; _offset = uint(_limit) + 1; } } splitArr = new string[](_splitsCount); _offset = 0; _splitsCount = 0; while (_offset < _baseBytes.length - 1) { int _limit = _indexOf(_base, _value, _offset); if (_limit == - 1) { _limit = int(_baseBytes.length); } string memory _tmp = new string(uint(_limit) - _offset); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for (uint i = _offset; i < uint(_limit); i++) { _tmpBytes[j++] = _baseBytes[i]; } _offset = uint(_limit) + 1; splitArr[_splitsCount++] = string(_tmpBytes); } return splitArr; } /** * Compare To * * Compares the characters of two strings, to ensure that they have an * identical footprint * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent */ function compareTo(string memory _base, string memory _value) internal pure returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for (uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i]) { return false; } } return true; } /** * Compare To Ignore Case (High gas cost) * * Compares the characters of two strings, converting them to the same case * where applicable to alphabetic characters to distinguish if the values * match. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent value * discarding case */ function compareToIgnoreCase(string memory _base, string memory _value) internal pure returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for (uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i] && _upper(_baseBytes[i]) != _upper(_valueBytes[i])) { return false; } } return true; } /** * Upper * * Converts all the values of a string to their corresponding upper case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to upper case * @return string */ function upper(string memory _base) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _upper(_baseBytes[i]); } return string(_baseBytes); } /** * Lower * * Converts all the values of a string to their corresponding lower case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to lower case * @return string */ function lower(string memory _base) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _lower(_baseBytes[i]); } return string(_baseBytes); } /** * Upper * * Convert an alphabetic character to upper case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to upper case * @return bytes1 The converted value if the passed value was alphabetic * and in a lower case otherwise returns the original value */ function _upper(bytes1 _b1) private pure returns (bytes1) { if (_b1 >= 0x61 && _b1 <= 0x7A) { return bytes1(uint8(_b1) - 32); } return _b1; } /** * Lower * * Convert an alphabetic character to lower case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to lower case * @return bytes1 The converted value if the passed value was alphabetic * and in a upper case otherwise returns the original value */ function _lower(bytes1 _b1) private pure returns (bytes1) { if (_b1 >= 0x41 && _b1 <= 0x5A) { return bytes1(uint8(_b1) + 32); } return _b1; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title PartnerFund * @notice Where partners’ fees are managed */ contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using Strings for string; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Partner { bytes32 nameHash; uint256 fee; address wallet; uint256 index; bool operatorCanUpdate; bool partnerCanUpdate; FungibleBalanceLib.Balance active; FungibleBalanceLib.Balance staged; TxHistoryLib.TxHistory txHistory; FullBalanceHistory[] fullBalanceHistory; } struct FullBalanceHistory { uint256 listIndex; int256 balance; uint256 blockNumber; } // // Variables // ----------------------------------------------------------------------------------------------------------------- Partner[] private partners; mapping(bytes32 => uint256) private _indexByNameHash; mapping(address => uint256) private _indexByWallet; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet); event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet); event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee); event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee); event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee); event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee); event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet); event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet); event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet); event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet); event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() external payable { _receiveEthersTo( indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive ethers to /// @param tag The tag of the concerned partner function receiveEthersTo(address tag, string memory) public payable { _receiveEthersTo( uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { _receiveTokensTo( indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Receive tokens to /// @param tag The tag of the concerned partner /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address tag, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { _receiveTokensTo( uint256(tag) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Hash name /// @param name The name to be hashed /// @return The hash value function hashName(string memory name) public pure returns (bytes32) { return keccak256(abi.encodePacked(name.upper())); } /// @notice Get deposit by partner and deposit indices /// @param partnerIndex The index of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByIndices(uint256 partnerIndex, uint256 depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Require partner index is one of registered partner require(0 < partnerIndex && partnerIndex <= partners.length, "Some error message when require fails [PartnerFund.sol:160]"); return _depositByIndices(partnerIndex - 1, depositIndex); } /// @notice Get deposit by partner name and deposit indices /// @param name The name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByName(string memory name, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name is registered return _depositByIndices(indexByName(name) - 1, depositIndex); } /// @notice Get deposit by partner name hash and deposit indices /// @param nameHash The hashed name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByNameHash(bytes32 nameHash, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name hash is registered return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex); } /// @notice Get deposit by partner wallet and deposit indices /// @param wallet The wallet of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByWallet(address wallet, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner wallet is registered return _depositByIndices(indexByWallet(wallet) - 1, depositIndex); } /// @notice Get deposits count by partner index /// @param index The index of the concerned partner /// return The deposits count function depositsCountByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:213]"); return _depositsCountByIndex(index - 1); } /// @notice Get deposits count by partner name /// @param name The name of the concerned partner /// return The deposits count function depositsCountByName(string memory name) public view returns (uint256) { // Implicitly require that partner name is registered return _depositsCountByIndex(indexByName(name) - 1); } /// @notice Get deposits count by partner name hash /// @param nameHash The hashed name of the concerned partner /// return The deposits count function depositsCountByNameHash(bytes32 nameHash) public view returns (uint256) { // Implicitly require that partner name hash is registered return _depositsCountByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get deposits count by partner wallet /// @param wallet The wallet of the concerned partner /// return The deposits count function depositsCountByWallet(address wallet) public view returns (uint256) { // Implicitly require that partner wallet is registered return _depositsCountByIndex(indexByWallet(wallet) - 1); } /// @notice Get active balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:265]"); return _activeBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByName(string memory name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name hash is registered return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:323]"); return _stagedBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByName(string memory name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get the number of partners /// @return The number of partners function partnersCount() public view returns (uint256) { return partners.length; } /// @notice Register a partner by name /// @param name The name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByName(string memory name, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Require not empty name string require(bytes(name).length > 0, "Some error message when require fails [PartnerFund.sol:392]"); // Hash name bytes32 nameHash = hashName(name); // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameEvent(name, fee, wallet); } /// @notice Register a partner by name hash /// @param nameHash The hashed name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet); } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByNameHash(bytes32 nameHash) public view returns (uint256) { uint256 index = _indexByNameHash[nameHash]; require(0 < index, "Some error message when require fails [PartnerFund.sol:431]"); return index; } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByName(string memory name) public view returns (uint256) { return indexByNameHash(hashName(name)); } /// @notice Gets the 1-based index of partner by its wallet /// @dev Reverts if wallet does not correspond to registered partner /// @return Index of partner by given wallet function indexByWallet(address wallet) public view returns (uint256) { uint256 index = _indexByWallet[wallet]; require(0 < index, "Some error message when require fails [PartnerFund.sol:455]"); return index; } /// @notice Gauge whether a partner by the given name is registered /// @param name The name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByName(string memory name) public view returns (bool) { return (0 < _indexByNameHash[hashName(name)]); } /// @notice Gauge whether a partner by the given name hash is registered /// @param nameHash The hashed name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByNameHash(bytes32 nameHash) public view returns (bool) { return (0 < _indexByNameHash[nameHash]); } /// @notice Gauge whether a partner by the given wallet is registered /// @param wallet The wallet of the concerned partner /// @return true if partner is registered, else false function isRegisteredByWallet(address wallet) public view returns (bool) { return (0 < _indexByWallet[wallet]); } /// @notice Get the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @return The fee fraction function feeByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:501]"); return _partnerFeeByIndex(index - 1); } /// @notice Get the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @return The fee fraction function feeByName(string memory name) public view returns (uint256) { // Get fee, implicitly requiring that partner name is registered return _partnerFeeByIndex(indexByName(name) - 1); } /// @notice Get the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The fee fraction function feeByNameHash(bytes32 nameHash) public view returns (uint256) { // Get fee, implicitly requiring that partner name hash is registered return _partnerFeeByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @return The fee fraction function feeByWallet(address wallet) public view returns (uint256) { // Get fee, implicitly requiring that partner wallet is registered return _partnerFeeByIndex(indexByWallet(wallet) - 1); } /// @notice Set the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @param newFee The partner's fee fraction function setFeeByIndex(uint256 index, uint256 newFee) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:549]"); // Update fee uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee); // Emit event emit SetFeeByIndexEvent(index, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByName(string memory name, uint256 newFee) public { // Update fee, implicitly requiring that partner name is registered uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee); // Emit event emit SetFeeByNameEvent(name, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByNameHash(bytes32 nameHash, uint256 newFee) public { // Update fee, implicitly requiring that partner name hash is registered uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee); // Emit event emit SetFeeByNameHashEvent(nameHash, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @param newFee The partner's fee fraction function setFeeByWallet(address wallet, uint256 newFee) public { // Update fee, implicitly requiring that partner wallet is registered uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee); // Emit event emit SetFeeByWalletEvent(wallet, oldFee, newFee); } /// @notice Get the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return The wallet function walletByIndex(uint256 index) public view returns (address) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:606]"); return partners[index - 1].wallet; } /// @notice Get the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return The wallet function walletByName(string memory name) public view returns (address) { // Get wallet, implicitly requiring that partner name is registered return partners[indexByName(name) - 1].wallet; } /// @notice Get the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The wallet function walletByNameHash(bytes32 nameHash) public view returns (address) { // Get wallet, implicitly requiring that partner name hash is registered return partners[indexByNameHash(nameHash) - 1].wallet; } /// @notice Set the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return newWallet The partner's wallet function setWalletByIndex(uint256 index, address newWallet) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:642]"); // Update wallet address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet); // Emit event emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return newWallet The partner's wallet function setWalletByName(string memory name, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet); // Emit event emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return newWallet The partner's wallet function setWalletByNameHash(bytes32 nameHash, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet); // Emit event emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet); } /// @notice Set the new partner wallet by the given old partner wallet /// @param oldWallet The old wallet of the concerned partner /// @return newWallet The partner's new wallet function setWalletByWallet(address oldWallet, address newWallet) public { // Update wallet _setPartnerWalletByIndex(indexByWallet(oldWallet) - 1, newWallet); // Emit event emit SetPartnerWalletByWalletEvent(oldWallet, newWallet); } /// @notice Stage the amount for subsequent withdrawal /// @param amount The concerned amount to stage /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function stage(int256 amount, address currencyCt, uint256 currencyId) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]"); // Clamp amount to move amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId)); partners[index - 1].active.sub(amount, currencyCt, currencyId); partners[index - 1].staged.add(amount, currencyCt, currencyId); partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index - 1].fullBalanceHistory.push( FullBalanceHistory( partners[index - 1].txHistory.depositsCount() - 1, partners[index - 1].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit StageEvent(msg.sender, amount, currencyCt, currencyId); } /// @notice Withdraw the given amount from staged balance /// @param amount The concerned amount to withdraw /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:736]"); // Clamp amount to move amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId)); partners[index - 1].staged.sub(amount, currencyCt, currencyId); // Execute transfer if (address(0) == currencyCt && 0 == currencyId) msg.sender.transfer(uint256(amount)); else { TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId ) ); require(success, "Some error message when require fails [PartnerFund.sol:754]"); } // Emit event emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- /// @dev index is 0-based function _receiveEthersTo(uint256 index, int256 amount) private { // Require that index is within bounds require(index < partners.length, "Some error message when require fails [PartnerFund.sol:769]"); // Add to active partners[index].active.add(amount, address(0), 0); partners[index].txHistory.addDeposit(amount, address(0), 0); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(address(0), 0), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, address(0), 0); } /// @dev index is 0-based function _receiveTokensTo(uint256 index, int256 amount, address currencyCt, uint256 currencyId, string memory standard) private { // Require that index is within bounds require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]"); require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]"); // Execute transfer TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); require(success, "Some error message when require fails [PartnerFund.sol:805]"); // Add to active partners[index].active.add(amount, currencyCt, currencyId); partners[index].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId); } /// @dev partnerIndex is 0-based function _depositByIndices(uint256 partnerIndex, uint256 depositIndex) private view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(depositIndex < partners[partnerIndex].fullBalanceHistory.length, "Some error message when require fails [PartnerFund.sol:830]"); FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex]; (,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex); balance = entry.balance; blockNumber = entry.blockNumber; } /// @dev index is 0-based function _depositsCountByIndex(uint256 index) private view returns (uint256) { return partners[index].fullBalanceHistory.length; } /// @dev index is 0-based function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].active.get(currencyCt, currencyId); } /// @dev index is 0-based function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].staged.get(currencyCt, currencyId); } function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) private { // Require that the name is not previously registered require(0 == _indexByNameHash[nameHash], "Some error message when require fails [PartnerFund.sol:871]"); // Require possibility to update require(partnerCanUpdate || operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:874]"); // Add new partner partners.length++; // Reference by 1-based index uint256 index = partners.length; // Update partner map partners[index - 1].nameHash = nameHash; partners[index - 1].fee = fee; partners[index - 1].wallet = wallet; partners[index - 1].partnerCanUpdate = partnerCanUpdate; partners[index - 1].operatorCanUpdate = operatorCanUpdate; partners[index - 1].index = index; // Update name hash to index map _indexByNameHash[nameHash] = index; // Update wallet to index map _indexByWallet[wallet] = index; } /// @dev index is 0-based function _setPartnerFeeByIndex(uint256 index, uint256 fee) private returns (uint256) { uint256 oldFee = partners[index].fee; // If operator tries to change verify that operator has access if (isOperator()) require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:906]"); else { // Require that msg.sender is partner require(msg.sender == partners[index].wallet, "Some error message when require fails [PartnerFund.sol:910]"); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:913]"); } // Update stored fee partners[index].fee = fee; return oldFee; } // @dev index is 0-based function _setPartnerWalletByIndex(uint256 index, address newWallet) private returns (address) { address oldWallet = partners[index].wallet; // If address has not been set operator is the only allowed to change it if (oldWallet == address(0)) require(isOperator(), "Some error message when require fails [PartnerFund.sol:931]"); // Else if operator tries to change verify that operator has access else if (isOperator()) require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:935]"); else { // Require that msg.sender is partner require(msg.sender == oldWallet, "Some error message when require fails [PartnerFund.sol:939]"); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:942]"); // Require that new wallet is not zero-address if it can not be changed by operator require(partners[index].operatorCanUpdate || newWallet != address(0), "Some error message when require fails [PartnerFund.sol:945]"); } // Update stored wallet partners[index].wallet = newWallet; // Update address to tag map if (oldWallet != address(0)) _indexByWallet[oldWallet] = 0; if (newWallet != address(0)) _indexByWallet[newWallet] = index; return oldWallet; } // @dev index is 0-based function _partnerFeeByIndex(uint256 index) private view returns (uint256) { return partners[index].fee; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NahmiiTypesLib * @dev Data types of general nahmii character */ library NahmiiTypesLib { // // Enums // ----------------------------------------------------------------------------------------------------------------- enum ChallengePhase {Dispute, Closed} // // Structures // ----------------------------------------------------------------------------------------------------------------- struct OriginFigure { uint256 originId; MonetaryTypesLib.Figure figure; } struct IntendedConjugateCurrency { MonetaryTypesLib.Currency intended; MonetaryTypesLib.Currency conjugate; } struct SingleFigureTotalOriginFigures { MonetaryTypesLib.Figure single; OriginFigure[] total; } struct TotalOriginFigures { OriginFigure[] total; } struct CurrentPreviousInt256 { int256 current; int256 previous; } struct SingleTotalInt256 { int256 single; int256 total; } struct IntendedConjugateCurrentPreviousInt256 { CurrentPreviousInt256 intended; CurrentPreviousInt256 conjugate; } struct IntendedConjugateSingleTotalInt256 { SingleTotalInt256 intended; SingleTotalInt256 conjugate; } struct WalletOperatorHashes { bytes32 wallet; bytes32 operator; } struct Signature { bytes32 r; bytes32 s; uint8 v; } struct Seal { bytes32 hash; Signature signature; } struct WalletOperatorSeal { Seal wallet; Seal operator; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title DriipSettlementTypesLib * @dev Types for driip settlements */ library DriipSettlementTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- enum SettlementRole {Origin, Target} struct SettlementParty { uint256 nonce; address wallet; bool done; uint256 doneBlockNumber; } struct Settlement { string settledKind; bytes32 settledHash; SettlementParty origin; SettlementParty target; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title DriipSettlementState * @notice Where driip settlement state is managed */ contract DriipSettlementState is Ownable, Servable, CommunityVotable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public INIT_SETTLEMENT_ACTION = "init_settlement"; string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done"; string constant public SET_MAX_NONCE_ACTION = "set_max_nonce"; string constant public SET_FEE_TOTAL_ACTION = "set_fee_total"; // // Variables // ----------------------------------------------------------------------------------------------------------------- uint256 public maxDriipNonce; DriipSettlementTypesLib.Settlement[] public settlements; mapping(address => uint256[]) public walletSettlementIndices; mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex; mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce; mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap; bool public upgradesFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement); event CompleteSettlementPartyEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done, uint256 doneBlockNumber); event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency, uint256 maxNonce); event SetMaxDriipNonceEvent(uint256 maxDriipNonce); event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce); event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee); event FreezeUpgradesEvent(); event UpgradeSettlementEvent(DriipSettlementTypesLib.Settlement settlement); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the count of settlements function settlementsCount() public view returns (uint256) { return settlements.length; } /// @notice Get the count of settlements for given wallet /// @param wallet The address for which to return settlement count /// @return count of settlements for the provided wallet function settlementsCountByWallet(address wallet) public view returns (uint256) { return walletSettlementIndices[wallet].length; } /// @notice Get settlement of given wallet and index /// @param wallet The address for which to return settlement /// @param index The wallet's settlement index /// @return settlement for the provided wallet and index function settlementByWalletAndIndex(address wallet, uint256 index) public view returns (DriipSettlementTypesLib.Settlement memory) { require(walletSettlementIndices[wallet].length > index, "Index out of bounds [DriipSettlementState.sol:107]"); return settlements[walletSettlementIndices[wallet][index] - 1]; } /// @notice Get settlement of given wallet and wallet nonce /// @param wallet The address for which to return settlement /// @param nonce The wallet's nonce /// @return settlement for the provided wallet and index function settlementByWalletAndNonce(address wallet, uint256 nonce) public view returns (DriipSettlementTypesLib.Settlement memory) { require(0 != walletNonceSettlementIndex[wallet][nonce], "No settlement found for wallet and nonce [DriipSettlementState.sol:120]"); return settlements[walletNonceSettlementIndex[wallet][nonce] - 1]; } /// @notice Initialize settlement, i.e. create one if no such settlement exists /// for the double pair of wallets and nonces /// @param settledKind The kind of driip of the settlement /// @param settledHash The hash of driip of the settlement /// @param originWallet The address of the origin wallet /// @param originNonce The wallet nonce of the origin wallet /// @param targetWallet The address of the target wallet /// @param targetNonce The wallet nonce of the target wallet function initSettlement(string memory settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, address targetWallet, uint256 targetNonce) public onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION) { if ( 0 == walletNonceSettlementIndex[originWallet][originNonce] && 0 == walletNonceSettlementIndex[targetWallet][targetNonce] ) { // Create new settlement settlements.length++; // Get the 0-based index uint256 index = settlements.length - 1; // Update settlement settlements[index].settledKind = settledKind; settlements[index].settledHash = settledHash; settlements[index].origin.nonce = originNonce; settlements[index].origin.wallet = originWallet; settlements[index].target.nonce = targetNonce; settlements[index].target.wallet = targetWallet; // Emit event emit InitSettlementEvent(settlements[index]); // Store 1-based index value index++; walletSettlementIndices[originWallet].push(index); walletSettlementIndices[targetWallet].push(index); walletNonceSettlementIndex[originWallet][originNonce] = index; walletNonceSettlementIndex[targetWallet][targetNonce] = index; } } /// @notice Set the done of the given settlement role in the given settlement /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @param done The done flag function completeSettlementParty(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done) public onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:181]"); // Get the settlement party DriipSettlementTypesLib.SettlementParty storage party = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Update party done and done block number properties party.done = done; party.doneBlockNumber = done ? block.number : 0; // Emit event emit CompleteSettlementPartyEvent(wallet, nonce, settlementRole, done, party.doneBlockNumber); } /// @notice Gauge whether the settlement is done wrt the given wallet and nonce /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @return True if settlement is done for role, else false function isSettlementPartyDone(address wallet, uint256 nonce) public view returns (bool) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Return false if settlement does not exist if (0 == index) return false; // Return done return ( wallet == settlements[index - 1].origin.wallet ? settlements[index - 1].origin.done : settlements[index - 1].target.done ); } /// @notice Gauge whether the settlement is done wrt the given wallet, nonce /// and settlement role /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @return True if settlement is done for role, else false function isSettlementPartyDone(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (bool) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Return false if settlement does not exist if (0 == index) return false; // Get the settlement party DriipSettlementTypesLib.SettlementParty storage settlementParty = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Require that wallet is party of the right role require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:246]"); // Return done return settlementParty.done; } /// @notice Get the done block number of the settlement party with the given wallet and nonce /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @return The done block number of the settlement wrt the given settlement role function settlementPartyDoneBlockNumber(address wallet, uint256 nonce) public view returns (uint256) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:265]"); // Return done block number return ( wallet == settlements[index - 1].origin.wallet ? settlements[index - 1].origin.doneBlockNumber : settlements[index - 1].target.doneBlockNumber ); } /// @notice Get the done block number of the settlement party with the given wallet, nonce and settlement role /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @return The done block number of the settlement wrt the given settlement role function settlementPartyDoneBlockNumber(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (uint256) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]"); // Get the settlement party DriipSettlementTypesLib.SettlementParty storage settlementParty = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Require that wallet is party of the right role require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]"); // Return done block number return settlementParty.doneBlockNumber; } /// @notice Set the max (driip) nonce /// @param _maxDriipNonce The max nonce function setMaxDriipNonce(uint256 _maxDriipNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_ACTION) { maxDriipNonce = _maxDriipNonce; // Emit event emit SetMaxDriipNonceEvent(maxDriipNonce); } /// @notice Update the max driip nonce property from CommunityVote contract function updateMaxDriipNonceFromCommunityVote() public { uint256 _maxDriipNonce = communityVote.getMaxDriipNonce(); if (0 == _maxDriipNonce) return; maxDriipNonce = _maxDriipNonce; // Emit event emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce); } /// @notice Get the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The max nonce function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { return walletCurrencyMaxNonce[wallet][currency.ct][currency.id]; } /// @notice Set the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @param maxNonce The max nonce function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency, uint256 maxNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_ACTION) { // Update max nonce value walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce; // Emit event emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce); } /// @notice Get the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param currency The concerned currency /// @return The total fee function totalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency memory currency) public view returns (MonetaryTypesLib.NoncedAmount memory) { return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id]; } /// @notice Set the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param _totalFee The total fee function setTotalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency memory currency, MonetaryTypesLib.NoncedAmount memory _totalFee) public onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION) { // Update total fees value totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee; // Emit event emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee); } /// @notice Freeze all future settlement upgrades /// @dev This operation can not be undone function freezeUpgrades() public onlyDeployer { // Freeze upgrade upgradesFrozen = true; // Emit event emit FreezeUpgradesEvent(); } /// @notice Upgrade settlement from other driip settlement state instance function upgradeSettlement(string memory settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber, address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber) public onlyDeployer { // Require that upgrades have not been frozen require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]"); // Require that settlement has not been initialized/upgraded already require(0 == walletNonceSettlementIndex[originWallet][originNonce], "Settlement exists for origin wallet and nonce [DriipSettlementState.sol:416]"); require(0 == walletNonceSettlementIndex[targetWallet][targetNonce], "Settlement exists for target wallet and nonce [DriipSettlementState.sol:417]"); // Create new settlement settlements.length++; // Get the 0-based index uint256 index = settlements.length - 1; // Update settlement settlements[index].settledKind = settledKind; settlements[index].settledHash = settledHash; settlements[index].origin.nonce = originNonce; settlements[index].origin.wallet = originWallet; settlements[index].origin.done = originDone; settlements[index].origin.doneBlockNumber = originDoneBlockNumber; settlements[index].target.nonce = targetNonce; settlements[index].target.wallet = targetWallet; settlements[index].target.done = targetDone; settlements[index].target.doneBlockNumber = targetDoneBlockNumber; // Emit event emit UpgradeSettlementEvent(settlements[index]); // Store 1-based index value index++; walletSettlementIndices[originWallet].push(index); walletSettlementIndices[targetWallet].push(index); walletNonceSettlementIndex[originWallet][originNonce] = index; walletNonceSettlementIndex[targetWallet][targetNonce] = index; } }
Receive tokens amount The concerned amount currencyCt The address of the concerned currency contract (address(0) == ETH) currencyId The ID of the concerned currency (0 for ETH and ERC20) standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { _receiveTokensTo( indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard ); }
1,006,033
./full_match/1/0x9d28eA625A51F8F4046DE4e853E36988F2AAC634/sources/contracts/ModaPoolBase.sol
Used internally, mostly by children implementations, see unstake() _staker an address which un-stakes tokens (which previously staked them) _depositId deposit ID to unstake from, zero-indexed _amount amount of tokens to unstake/
function _unstake(address _staker, uint256 _depositId, uint256 _amount) internal virtual { require(_amount > 0, 'zero amount'); User storage user = users[_staker]; Deposit storage stakeDeposit = user.deposits[_depositId]; bool isYield = stakeDeposit.isYield; require(stakeDeposit.tokenAmount >= _amount, 'amount exceeds stake'); _processRewards(_staker); uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = stakeDeposit.lockedUntil == 0 ? WEIGHT_MULTIPLIER * (stakeDeposit.tokenAmount - _amount) : ((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) / 365 days + 1) * (WEIGHT_MULTIPLIER * (stakeDeposit.tokenAmount - _amount)); if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; usersLockingWeight = usersLockingWeight - previousWeight + newWeight; if (isYield) { modaPoolFactory.mintYieldTo(msg.sender, _amount); transferPoolToken(msg.sender, _amount); } emit Unstaked(msg.sender, _staker, _amount); }
17,110,330
./full_match/100/0x6369F971fd1f1f230B8584151Ed7747FF710Cc68/sources/contracts/core/connext/facets/SwapAdminFacet.sol
StableSwap ADMIN FUNCTIONS / Initializes this Swap contract with the given parameters. This will also clone a LPToken contract that represents users' LP positions. The owner of LPToken will be this contract - which means only this contract is allowed to mint/burn tokens. The swap can only be updated after initialization via `rampA`. This means if this value is incorrectly set, it will take some time to reach the correct value. _key the hash of the canonical id and domain for token _pooledTokens an array of ERC20s this pool will accept. length of this array should be in 2 ~ 16 decimals the decimals to use for each pooled token, eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS(18) Only fixed decimal tokens are allowed. lpTokenName the long-form name of the token to be deployed lpTokenSymbol the short symbol for the token to be deployed _a the amplification coefficient n (n - 1). See the StableSwap paper for details _fee default swap fee to be initialized with _adminFee default adminFee to be initialized with/ Check _pooledTokens and precisions parameter Check if index is already used. Check if 0th element is a duplicate. Initialize swapStorage struct
function initializeSwap( bytes32 _key, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee ) external onlyOwnerOrAdmin { if (s.swapStorages[_key].pooledTokens.length != 0) revert SwapAdminFacet__initializeSwap_alreadyInitialized(); if ( _pooledTokens.length < Constants.MINIMUM_POOLED_TOKENS || _pooledTokens.length > Constants.MAXIMUM_POOLED_TOKENS ) { revert SwapAdminFacet__initializeSwap_invalidPooledTokens(); } uint256 numPooledTokens = _pooledTokens.length; if (numPooledTokens != decimals.length) revert SwapAdminFacet__initializeSwap_decimalsMismatch(); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint256 i; i < numPooledTokens; ) { if (i != 0) { if (s.tokenIndexes[_key][address(_pooledTokens[i])] != 0 || _pooledTokens[0] == _pooledTokens[i]) revert SwapAdminFacet__initializeSwap_duplicateTokens(); } if (address(_pooledTokens[i]) == address(0)) revert SwapAdminFacet__initializeSwap_zeroTokenAddress(); if (decimals[i] > Constants.POOL_PRECISION_DECIMALS) revert SwapAdminFacet__initializeSwap_tokenDecimalsExceedMax(); precisionMultipliers[i] = 10**uint256(Constants.POOL_PRECISION_DECIMALS - decimals[i]); unchecked { ++i; } } if (_fee > Constants.MAX_SWAP_FEE - 1) revert SwapAdminFacet__initializeSwap_feeExceedMax(); if (_adminFee > Constants.MAX_ADMIN_FEE - 1) revert SwapAdminFacet__initializeSwap_adminFeeExceedMax(); if (!lpToken.initialize(lpTokenName, lpTokenSymbol)) revert SwapAdminFacet__initializeSwap_failedInitLpTokenClone(); SwapUtils.Swap memory entry = SwapUtils.Swap({ key: _key, initialA: _a * Constants.A_PRECISION, futureA: _a * Constants.A_PRECISION, swapFee: _fee, adminFee: _adminFee, lpToken: lpToken, pooledTokens: _pooledTokens, tokenPrecisionMultipliers: precisionMultipliers, balances: new uint256[](_pooledTokens.length), adminFees: new uint256[](_pooledTokens.length), initialATime: 0, futureATime: 0, disabled: false, removeTime: 0 }); s.swapStorages[_key] = entry; emit SwapInitialized(_key, entry, msg.sender); }
14,284,271