Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
11
// A single function endpoint for loading the starting/ point of the range for each accepted grant/This is modified any time a grant is accepted/ return returns the starting point uint
function _loadBound() internal pure returns (Storage.Uint256 memory) { // This call returns a storage mapping with a unique non overwrite-able storage location // which can be persisted through upgrades, even if they change storage layout return Storage.uint256Ptr("bound"); }
function _loadBound() internal pure returns (Storage.Uint256 memory) { // This call returns a storage mapping with a unique non overwrite-able storage location // which can be persisted through upgrades, even if they change storage layout return Storage.uint256Ptr("bound"); }
27,443
343
// New gen0 auction price will not be less than the starting price always.
if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; }
if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; }
17,453
57
// Transfer ETH
function REPAYETH964(address accountAddress, uint256 asset) private { //inject NONSTANDARD NAMING address payable addr = accountAddress.MAKE_PAYABLE861(); addr.transfer(asset); }
function REPAYETH964(address accountAddress, uint256 asset) private { //inject NONSTANDARD NAMING address payable addr = accountAddress.MAKE_PAYABLE861(); addr.transfer(asset); }
42,764
0
// It takes at least 3minExitPeriod before each new exit game contract is able to start protecting existing transactions /
constructor (uint256 _minExitPeriod, uint256 _initialImmuneExitGames) public
constructor (uint256 _minExitPeriod, uint256 _initialImmuneExitGames) public
49,531
65
// given the cumulative prices of the start and end of a period, and the length of the period, compute the average price in terms of how much amount out is received for the amount in
function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn
function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn
39,906
461
// Gets the current list of External ERC721 tokens that will be awarded with the current prize/ return An array of External ERC721 token addresses
function getExternalErc721Awards() external view returns (address[] memory) { return externalErc721s.addressArray(); }
function getExternalErc721Awards() external view returns (address[] memory) { return externalErc721s.addressArray(); }
16,513
94
// _gonsPerFragment = TOTAL_GONS.div(_totalSupply);
_gonsPerFragment = _gonsPerFragment.mul(_totalSupply); _gonsPerFragment = _gonsPerFragment.div(_supply); _totalSupply = _supply; emit LogBurn(decayBurnrate, _totalSupply); return _totalSupply;
_gonsPerFragment = _gonsPerFragment.mul(_totalSupply); _gonsPerFragment = _gonsPerFragment.div(_supply); _totalSupply = _supply; emit LogBurn(decayBurnrate, _totalSupply); return _totalSupply;
39,810
11
// Fees will be down in future if platform works well
function feesDown(uint8 newFees) external onlyOwner { require (activeBets.length == 0, "All bets should be processed (complete or canceled) before Fees changes."); fees=newFees; }
function feesDown(uint8 newFees) external onlyOwner { require (activeBets.length == 0, "All bets should be processed (complete or canceled) before Fees changes."); fees=newFees; }
27,011
17
// Return the current unlock-phase. Won&39;t work until after the contract/ has `finalise()` called.
function currentPhase() public constant returns (uint)
function currentPhase() public constant returns (uint)
33,029
6
// qualquer coisa/ seu textão
contract Aluguel { string public locatario; string public locador; uint256 private valor; uint256 constant NumeroMaximoLegaldeAlugueisParaMulta = 3; constructor(string memory nomeLocador, string memory nomeLocatario, uint256 valorDoAluguel) public { locador = nomeLocador; locatario = nomeLocatario; valor = valorDoAluguel; } function ValorAtualdoaluguel() public view returns (uint256) { return valor; } function simulaMulta (uint256 mesesRestantes, uint256 totalMesesContrato) public view returns (uint256 valorMulta) { valorMulta = valor*NumeroMaximoLegaldeAlugueisParaMulta; valorMulta = valorMulta/totalMesesContrato; valorMulta = valorMulta*mesesRestantes; return valorMulta; } function reajustaAluguel(uint256 percentualReajuste) public { if (percentualReajuste > 20){ percentualReajuste = 20; } uint256 valorDoAcrescimo = 0; valorDoAcrescimo = ((valor*percentualReajuste)/100); valor = valor + valorDoAcrescimo; } function aditamentoValorAluguel(uint256 valorCerto) public { valor = valorCerto; } function aplicaMulta(uint256 mesesRestantes, uint256 percentual) public{ require(mesesRestantes<30, "Período de contrato inválido"); for (uint i=1; i<mesesRestantes; i++) { valor = valor+((valor*percentual)/100); } } }
contract Aluguel { string public locatario; string public locador; uint256 private valor; uint256 constant NumeroMaximoLegaldeAlugueisParaMulta = 3; constructor(string memory nomeLocador, string memory nomeLocatario, uint256 valorDoAluguel) public { locador = nomeLocador; locatario = nomeLocatario; valor = valorDoAluguel; } function ValorAtualdoaluguel() public view returns (uint256) { return valor; } function simulaMulta (uint256 mesesRestantes, uint256 totalMesesContrato) public view returns (uint256 valorMulta) { valorMulta = valor*NumeroMaximoLegaldeAlugueisParaMulta; valorMulta = valorMulta/totalMesesContrato; valorMulta = valorMulta*mesesRestantes; return valorMulta; } function reajustaAluguel(uint256 percentualReajuste) public { if (percentualReajuste > 20){ percentualReajuste = 20; } uint256 valorDoAcrescimo = 0; valorDoAcrescimo = ((valor*percentualReajuste)/100); valor = valor + valorDoAcrescimo; } function aditamentoValorAluguel(uint256 valorCerto) public { valor = valorCerto; } function aplicaMulta(uint256 mesesRestantes, uint256 percentual) public{ require(mesesRestantes<30, "Período de contrato inválido"); for (uint i=1; i<mesesRestantes; i++) { valor = valor+((valor*percentual)/100); } } }
10,378
20
// ICO contract address setter
function setIcoContractAddress(address _icoContractAddress) public onlyOwner
function setIcoContractAddress(address _icoContractAddress) public onlyOwner
30,648
4
// global counter of vaultIds
Counters.Counter private _globalIndex;
Counters.Counter private _globalIndex;
14,849
260
// send share for opk to divies
if (_opk > 0) Divies.deposit.value(_opk)();
if (_opk > 0) Divies.deposit.value(_opk)();
41,943
210
// Throws if operator is not whitelisted./
modifier onlyManager() { checkRole(msg.sender, ROLE_MANAGER); _; }
modifier onlyManager() { checkRole(msg.sender, ROLE_MANAGER); _; }
26,883
30
// else remain at 0 until volume decreases
} else {
} else {
4,504
25
// Actualiza el totalSupply
totalSupply -= _value; emit Burn(_value); return true;
totalSupply -= _value; emit Burn(_value); return true;
15,549
99
// Make a fee contribution. It cannot be inlined in fundAppeal because of the stack limit. _itemID The item receiving the contribution. _requestID The request to contribute. _roundID The round to contribute. _side The side for which to contribute. _contributor The contributor. _amount The amount contributed. _totalRequired The total amount required for this side.return The amount of appeal fees contributed. /
function contribute( bytes32 _itemID, uint256 _requestID, uint256 _roundID, uint256 _side, address payable _contributor, uint256 _amount, uint256 _totalRequired
function contribute( bytes32 _itemID, uint256 _requestID, uint256 _roundID, uint256 _side, address payable _contributor, uint256 _amount, uint256 _totalRequired
39,873
27
// Returns the buy price details for an NFT if one is available. If no price is found, seller will be address(0) and price will be max uint256. nftContract The address of the NFT contract. tokenId The id of the NFT.return seller The address of the owner that listed a buy price for this NFT.Returns `address(0)` if there is no buy price set for this NFT.return price The price of the NFT.Returns max uint256 if there is no buy price set for this NFT (since a price of 0 is supported). /
function getBuyPrice(address nftContract, uint256 tokenId) external view returns (address seller, uint256 price) { seller = nftContractToTokenIdToBuyPrice[nftContract][tokenId].seller; if (seller == address(0)) { return (seller, type(uint256).max); } price = nftContractToTokenIdToBuyPrice[nftContract][tokenId].price; }
function getBuyPrice(address nftContract, uint256 tokenId) external view returns (address seller, uint256 price) { seller = nftContractToTokenIdToBuyPrice[nftContract][tokenId].seller; if (seller == address(0)) { return (seller, type(uint256).max); } price = nftContractToTokenIdToBuyPrice[nftContract][tokenId].price; }
16,170
75
// Caller must be the router owner
if (msg.sender != getRouterOwner(_router)) revert RoutersFacet__removeRouterLiquidityFor_notOwner();
if (msg.sender != getRouterOwner(_router)) revert RoutersFacet__removeRouterLiquidityFor_notOwner();
7,272
25
// "1000000000000000","1000000000000001",["0x651226B6a1855113101bc4A6E818479D69F0b190","0x4e9475DA3784B81aE142717973c31E3E0bDc8e5D","0x651226B6a1855113101bc4A6E818479D69F0b190"],["0x9fCb53A9b38A215e659A66380C47012eE8A163b7","0x9a603b9f44e8939618e54f04ddcc94d0f29ad423"],[3,3]0x029fCb53A9b38A215e659A66380C47012eE8A163b79a603b9f44e8939618e54f04ddcc94d0f29ad423000003830000000000000000000000430000"1000000000000000","1000000000000001",["0x651226B6a1855113101bc4A6E818479D69F0b190","0x4e9475DA3784B81aE142717973c31E3E0bDc8e5D","0xFca8782144884b644515FC0292c60E7313fB7AD0","0x651226B6a1855113101bc4A6E818479D69F0b190"],["0x9fCb53A9b38A215e659A66380C47012eE8A163b7","0xd71E12c46C9FE07Ba4711045eDDcd4d7b3FEb4b1","0xB0F0B15Eb78588Cb658FA45cE86671165c733D16"],[3,"3",3]0x039fCb53A9b38A215e659A66380C47012eE8A163b7d71E12c46C9FE07Ba4711045eDDcd4d7b3FEb4b1B0F0B15Eb78588Cb658FA45cE86671165c733D160000000383030000000000000000000000430000651226B6a1855113101bc4A6E818479D69F0b190
mapping (uint=>mapping(address=>uint)) public _positions;
mapping (uint=>mapping(address=>uint)) public _positions;
17,285
141
// Initialize the cumulativeFeeFactor when adding fees for the first time
if (earningsPool.cumulativeFeeFactor == 0) { earningsPool.cumulativeFeeFactor = prevCumulativeFeeFactor.add( PreciseMathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake) ); return; }
if (earningsPool.cumulativeFeeFactor == 0) { earningsPool.cumulativeFeeFactor = prevCumulativeFeeFactor.add( PreciseMathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake) ); return; }
23,848
72
// The number must fit in the mantissa.
require(number < 2 << 24, 'OS_OVERFLOW_FLOAT_ENCODE');
require(number < 2 << 24, 'OS_OVERFLOW_FLOAT_ENCODE');
37,969
13
// Address of the implementation for the staking purchaser contract. Used to buy NFTs at a steep discount by/ staking mTokens.
address stakingPurchaser;
address stakingPurchaser;
42,800
0
// List of buyers to prevent multiple purchases /Triggers when all payments are successfully doneevent ProductBought(address buyer, uint256 quantity, string clientId);
function AirdropCampaign( MintableToken _token, string _name, uint32 _maxUnits, uint8 _bronzeReward, uint8 _silverReward, uint8 _goldReward, uint8 _silverDistance, uint8 _goldDistance,
function AirdropCampaign( MintableToken _token, string _name, uint32 _maxUnits, uint8 _bronzeReward, uint8 _silverReward, uint8 _goldReward, uint8 _silverDistance, uint8 _goldDistance,
5,932
208
// Withdraw an amount of underlying to the vault. This can only be called by the vault. If the amount is not available, it will be made liquid. amount Amount of underlying to withdraw.return True if successful withdrawal. /
function withdraw(uint256 amount) external override onlyVault returns (bool) { if (amount == 0) return false; uint256 underlyingBalance = _underlyingBalance(); // Transferring from idle balance if enough if (underlyingBalance >= amount) { if (!vault.send(amount)) return false; emit Withdraw(amount); return true; } // Unstaking needed LP Tokens from Convex uint256 requiredUnderlyingAmount = amount - underlyingBalance; uint256 maxLpBurned = _maxLpBurned(requiredUnderlyingAmount); uint256 requiredLpAmount = maxLpBurned - _lpBalance(); if (!rewards.withdrawAndUnwrap(requiredLpAmount, false)) return false; // Removing needed liquidity from Curve uint256[2] memory amounts; // solhint-disable-next-line reentrancy amounts[curveIndex] = requiredUnderlyingAmount; curvePool.remove_liquidity_imbalance(amounts, maxLpBurned); vault.transfer(amount); emit Withdraw(amount); return true; }
function withdraw(uint256 amount) external override onlyVault returns (bool) { if (amount == 0) return false; uint256 underlyingBalance = _underlyingBalance(); // Transferring from idle balance if enough if (underlyingBalance >= amount) { if (!vault.send(amount)) return false; emit Withdraw(amount); return true; } // Unstaking needed LP Tokens from Convex uint256 requiredUnderlyingAmount = amount - underlyingBalance; uint256 maxLpBurned = _maxLpBurned(requiredUnderlyingAmount); uint256 requiredLpAmount = maxLpBurned - _lpBalance(); if (!rewards.withdrawAndUnwrap(requiredLpAmount, false)) return false; // Removing needed liquidity from Curve uint256[2] memory amounts; // solhint-disable-next-line reentrancy amounts[curveIndex] = requiredUnderlyingAmount; curvePool.remove_liquidity_imbalance(amounts, maxLpBurned); vault.transfer(amount); emit Withdraw(amount); return true; }
62,291
35
// approve this contract to transfer Alices NFT to Bob later. IERC721(alicesNFT).approve(this, ATokenID); not sure which one is right! this is where the error is!
IERC721(alicesNFT).approve(bob, ATokenID); emit approved(msg.sender, "IERC721(alicesNFT).Name()", bob);
IERC721(alicesNFT).approve(bob, ATokenID); emit approved(msg.sender, "IERC721(alicesNFT).Name()", bob);
30,103
13
// can only withdraw at most our initial balance per withdraw call
uint256 toWithdraw = initialDeposit < challengeTotalRemainingBalance ? initialDeposit : challengeTotalRemainingBalance; challenge.withdraw(toWithdraw);
uint256 toWithdraw = initialDeposit < challengeTotalRemainingBalance ? initialDeposit : challengeTotalRemainingBalance; challenge.withdraw(toWithdraw);
28,140
19
// Time when auction started NOTE: 0 if this auction has been concluded
uint40 startedAt;
uint40 startedAt;
2,993
511
// Transmutes and unstakes all waTokens// This function combines the transmute and unstake functions for ease of use
function exit() public { transmute(); uint256 toWithdraw = depositedWaTokens[msg.sender]; unstake(toWithdraw); }
function exit() public { transmute(); uint256 toWithdraw = depositedWaTokens[msg.sender]; unstake(toWithdraw); }
51,352
179
// A base type has the NF bit but does has an index.
return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK != 0);
return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK != 0);
29,027
61
// Adds an address to the list of emergency liquidators/liquidator The address to add to the list/Emergency liquidators are trusted addresses/ that are able to liquidate positions while the contracts are paused,/ e.g. when there is a risk of bad debt while an exploit is being patched./ In the interest of fairness, emergency liquidators do not receive a premium/ And are compensated by the Gearbox DAO separately.
function addEmergencyLiquidator(address liquidator) external;
function addEmergencyLiquidator(address liquidator) external;
28,697
32
// We mint to contributor account and lock the tokens. Theoretically, the price is increasing (up to P1), but since we are in the hatching phase, the actual price will stay P0. The contract will hold the locked tokens.
function _mintInternalAndLock( address _adr, uint256 _amount ) internal
function _mintInternalAndLock( address _adr, uint256 _amount ) internal
33,623
11
// _time == midTime
return midValue;
return midValue;
19,642
194
// fixed-term loan, so need to query iToken for latest variable rate
uint256 owedPerDay = loanLocal.principal .mul(ILoanPool(loanLocal.lender).borrowInterestRate()) .div(DAYS_IN_A_YEAR * WEI_PERCENT_PRECISION); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .add(owedPerDay); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .sub(loanInterestLocal.owedPerDay); loanInterestLocal.owedPerDay = owedPerDay;
uint256 owedPerDay = loanLocal.principal .mul(ILoanPool(loanLocal.lender).borrowInterestRate()) .div(DAYS_IN_A_YEAR * WEI_PERCENT_PRECISION); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .add(owedPerDay); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .sub(loanInterestLocal.owedPerDay); loanInterestLocal.owedPerDay = owedPerDay;
59,301
22
// Returns a slice from a byte array without preserving the input./b The byte array to take a slice from. Will be destroyed in the process./from The starting index for the slice (inclusive)./to The final index for the slice (exclusive)./ return result The slice containing bytes at indices [from, to)/When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(
function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(
846
41
// Voting started and in progress /
modifier votingInProgress() { if (isVoting == false) revert(); _; }
modifier votingInProgress() { if (isVoting == false) revert(); _; }
24,898
39
// set and update that token in the mapping
allDivinityXs[_tokenId] = divinityx;
allDivinityXs[_tokenId] = divinityx;
8,431
184
// max amount of stkTRU than can be unstaked after current cooldown period is over /
function unstakable(address staker) public view returns (uint256) { if (unlockTime(staker) == type(uint256).max) { return balanceOf[staker]; } if (receivedDuringCooldown[staker] > balanceOf[staker]) { return 0; } return balanceOf[staker].sub(receivedDuringCooldown[staker]); }
function unstakable(address staker) public view returns (uint256) { if (unlockTime(staker) == type(uint256).max) { return balanceOf[staker]; } if (receivedDuringCooldown[staker] > balanceOf[staker]) { return 0; } return balanceOf[staker].sub(receivedDuringCooldown[staker]); }
54,111
14
// addLiquidity function which interact with Uniswap v3 /
function _addLiquidity( uint256 _tokenId, address _token0, address _token1, uint256 _amount0, uint256 _amount1, uint256 _slippage ) internal returns (
function _addLiquidity( uint256 _tokenId, address _token0, address _token1, uint256 _amount0, uint256 _amount1, uint256 _slippage ) internal returns (
43,813
21
// CALCULATE BURN OR STAKING %/
function calculatePercentage(uint256 amount, uint256 percentage, uint256 selecteWinnerPrecision) public pure returns(uint256){ return amount.mul(selecteWinnerPrecision).mul(percentage).div(100).div(selecteWinnerPrecision); }
function calculatePercentage(uint256 amount, uint256 percentage, uint256 selecteWinnerPrecision) public pure returns(uint256){ return amount.mul(selecteWinnerPrecision).mul(percentage).div(100).div(selecteWinnerPrecision); }
34,057
46
// Upgrade the backing implementation of the proxy and call a function on it.
function upgradeToAndCall(address logic, bytes calldata data) external payable override ifAdmin { _upgradeTo(logic); Address.functionDelegateCall(logic, data); }
function upgradeToAndCall(address logic, bytes calldata data) external payable override ifAdmin { _upgradeTo(logic); Address.functionDelegateCall(logic, data); }
48,151
45
// Version 11.2
contract RxNftMinter is ERC721Base { uint256 private rx_tokenCounter; constructor( string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps ) ERC721Base(_name, _symbol, _royaltyRecipient, _royaltyBps) { rx_tokenCounter = 0; add(admins, msg.sender); } struct Script { address patient_address; string name; string description; string medication; string dob; uint256 quantity; uint256 quantityFilled; uint256 rxId; string datePrescribed; string dateFilled; string dateNextFill; } mapping(uint256 => Script) public scripts; Script[] allScripts; event ScriptWritten ( address indexed patient_wallet, string patient_name, string medication, uint256 quantity, uint256 quantityFilled, string datePrescribed, uint256 dateRxStart, uint256 indexed script_token_number ); event ScriptSentToPt ( address indexed patient_wallet, address indexed doctor_wallet, uint256 indexed script_token_number ); event UpdateScriptQuantityAndDatesEvent( uint256 quantity_prescribed, uint256 indexed quantity_filled, uint256 quantity_filled_today, uint256 quantity_unfilled, string date_filled, string next_available_fill_date, uint256 script_token_number, address indexed pharmacy_address, address indexed patient_address ); event PatientTransferToPharmacy( address indexed patient_address, address indexed pharmacy_address, uint256 indexed script_token_number ); event PharmacyTransferToPatient( address indexed pharmacy_address, address indexed patient_address, uint256 indexed script_token_number ); // ** Roles ** struct Role { mapping(address => bool) bearer; } Role private patients; Role private pharmacies; Role private doctors; Role private admins; function add(Role storage _role, address _account) internal { require(!has(_role, _account), "Roles: Account has role"); _role.bearer[_account] = true; } function remove(Role storage _role, address _account) internal { require(has(_role, _account), "Roles: Account does NOT have role"); _role.bearer[_account] = false; } //Check if account HAS Role: 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]; } // ** Set Modifiers ** modifier onlyPatient() { // require(patients.has(patients, address) == true, "Must have patient role."); require(has(patients, msg.sender) == true, "Must have patient role."); _; } modifier onlyPharmacy() { require(has(pharmacies, msg.sender) == true, "Must have Pharmacy role."); _; } modifier onlyDoctor() { require(has(doctors, msg.sender) == true, "Must have Doctor role."); _; } modifier onlyAdmin() { require(has(admins, msg.sender) == true, "Must have Admin role."); _; } function addPatient(address _newPatient) external onlyAdmin { add(patients, _newPatient); } function addPharmacy(address _newPharmacy) external onlyAdmin { add(pharmacies, _newPharmacy); } function addDoctor(address _newDoctor) external onlyAdmin { add(doctors, _newDoctor); } function addAdmin(address _newAdmin) external onlyAdmin { add(admins, _newAdmin); } // // Remove Roles function removePatient(address _oldPatient) external onlyAdmin { remove(patients, _oldPatient); } function removePharmacy(address _oldPharmacy) external onlyAdmin { remove(pharmacies, _oldPharmacy); } function removeDoctor(address _oldDoctor) external onlyAdmin { remove(doctors, _oldDoctor); } function _createScript( // string memory _patient_wallet, address _patient_address, string memory _name, string memory _description, string memory _medication, string memory _dob, // string memory _quantity, uint256 _quantity, // uint256 _quantityPrescribed, // string memory _npi, // string memory _dea string memory _datePrescribed, uint256 _dateRxStart // string memory _dateFilled, // uint256 _dateRxEnd, // string memory _dateNextFill, // uint256 _dateRxNext ) public returns (uint256) { Script memory _rx = Script({ // patient_wallet: _patient_wallet, patient_address: _patient_address, name: _name, description: _description, medication: _medication, dob: _dob, quantity: _quantity, quantityFilled: 0, // assume quantity filled always zero when script written. rxId: rx_tokenCounter, datePrescribed: _datePrescribed, // string datePrescribed; // dateRxStart: _dateRxStart, // uint256 dateRxStart; dateFilled: 'N/A', // string dateFilled; // dateRxEnd: 0, // uint256 dateRxEnd; dateNextFill: 'N/A' // string dateNextFill (daysLeft); // dateRxNext: 0 // uint256 dateRxNext; // dea: _dea }); allScripts.push(_rx); emit ScriptWritten( //_patient_wallet, //address ("string") _patient_address, //address ('string') declared as 'address' in _createScript _name, //string _medication, //string _quantity, //uint256 0, //quantityFilled uint256 _datePrescribed, // string date _dateRxStart, // uint256 date rx_tokenCounter // uint256 tokenId ); // _transfer(address(0), _rx.patient_wallet, _rx.rxId); // emit Transfer(address(0), _rx.patient_wallet, _rx.rxId); // mintRx(_rx.patient_wallet, _rx.rxId); // mintRx(_patient_address, rx_tokenCounter); return _rx.rxId; } function mintRx(address _to ) public { _safeMint(_to, 1); emit ScriptSentToPt( _to, msg.sender, rx_tokenCounter ); rx_tokenCounter += 1; } function transferPatientToPharmacy(address _from, address _to, uint256 tokenId) public { safeTransferFrom(_from, _to, tokenId); emit PatientTransferToPharmacy ( _from, _to, tokenId ); } function transferPatientToPharmacyRoles(address _from, address _to, uint256 tokenId) public onlyPatient { safeTransferFrom(_from, _to, tokenId); emit PatientTransferToPharmacy ( _from, _to, tokenId ); } function transferPharmacyToPatient(address _from, address _to, uint256 tokenId) public { safeTransferFrom(_from, _to, tokenId); emit PharmacyTransferToPatient ( _from, _to, tokenId ); } function transferPharmacyToPatientRoles(address _from, address _to, uint256 tokenId) public onlyPharmacy { safeTransferFrom(_from, _to, tokenId); emit PharmacyTransferToPatient ( _from, _to, tokenId ); } //*********************************************************************************************************** */ function _baseURI() internal pure override returns (string memory) { return "data:application/json;base64,"; } function tokenSVGImageURI(uint256 tokenId) public view returns (string memory) { string[7] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: black; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="#E8F559" /><text x="10" y="20" class="base">'; // parts[1] = getPatientInfo(tokenId); parts[1] = getQuantityInfo(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getMedicationInfo(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getDateInfo(tokenId); parts[6] = "</text></svg>"; // string memory output = string( string memory output = string( abi.encodePacked( parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6] ) ); return string(abi.encodePacked("data:image/svg+xml;base64,", Base64.encode(bytes(output)))); } function tokenURI( uint256 tokenId ) public view override returns (string memory) { string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name":"', getPatientName(tokenId), '","description":"', getSig(tokenId), // '",', '","medication":"', getMedication(tokenId), // '",', '","quantity":"', getQuantity(tokenId), // '",', '","quantityfilled":"', getQuantityFilled(tokenId), // '",', // '", "image": "data:image/svg+xml;base64,', // Base64.encode(bytes(output)), '", "image":"', tokenSVGImageURI(tokenId), '"}' // '",', // '"attributes": [{"trait_type": "npi", "value": "01010101"},{"trait_type": "state", "value": "CA"},{"trait_type": "expiration", "value": "06/06/2023"}]}' // '"attributes":', // jsonAttributes, // "}" ) ) ) ); // return // output = string(abi.encodePacked(_baseURI(),)); string memory output = string(abi.encodePacked("data:application/json;base64,", json)); return output; } //end of tokenURI or generateSVG
contract RxNftMinter is ERC721Base { uint256 private rx_tokenCounter; constructor( string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps ) ERC721Base(_name, _symbol, _royaltyRecipient, _royaltyBps) { rx_tokenCounter = 0; add(admins, msg.sender); } struct Script { address patient_address; string name; string description; string medication; string dob; uint256 quantity; uint256 quantityFilled; uint256 rxId; string datePrescribed; string dateFilled; string dateNextFill; } mapping(uint256 => Script) public scripts; Script[] allScripts; event ScriptWritten ( address indexed patient_wallet, string patient_name, string medication, uint256 quantity, uint256 quantityFilled, string datePrescribed, uint256 dateRxStart, uint256 indexed script_token_number ); event ScriptSentToPt ( address indexed patient_wallet, address indexed doctor_wallet, uint256 indexed script_token_number ); event UpdateScriptQuantityAndDatesEvent( uint256 quantity_prescribed, uint256 indexed quantity_filled, uint256 quantity_filled_today, uint256 quantity_unfilled, string date_filled, string next_available_fill_date, uint256 script_token_number, address indexed pharmacy_address, address indexed patient_address ); event PatientTransferToPharmacy( address indexed patient_address, address indexed pharmacy_address, uint256 indexed script_token_number ); event PharmacyTransferToPatient( address indexed pharmacy_address, address indexed patient_address, uint256 indexed script_token_number ); // ** Roles ** struct Role { mapping(address => bool) bearer; } Role private patients; Role private pharmacies; Role private doctors; Role private admins; function add(Role storage _role, address _account) internal { require(!has(_role, _account), "Roles: Account has role"); _role.bearer[_account] = true; } function remove(Role storage _role, address _account) internal { require(has(_role, _account), "Roles: Account does NOT have role"); _role.bearer[_account] = false; } //Check if account HAS Role: 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]; } // ** Set Modifiers ** modifier onlyPatient() { // require(patients.has(patients, address) == true, "Must have patient role."); require(has(patients, msg.sender) == true, "Must have patient role."); _; } modifier onlyPharmacy() { require(has(pharmacies, msg.sender) == true, "Must have Pharmacy role."); _; } modifier onlyDoctor() { require(has(doctors, msg.sender) == true, "Must have Doctor role."); _; } modifier onlyAdmin() { require(has(admins, msg.sender) == true, "Must have Admin role."); _; } function addPatient(address _newPatient) external onlyAdmin { add(patients, _newPatient); } function addPharmacy(address _newPharmacy) external onlyAdmin { add(pharmacies, _newPharmacy); } function addDoctor(address _newDoctor) external onlyAdmin { add(doctors, _newDoctor); } function addAdmin(address _newAdmin) external onlyAdmin { add(admins, _newAdmin); } // // Remove Roles function removePatient(address _oldPatient) external onlyAdmin { remove(patients, _oldPatient); } function removePharmacy(address _oldPharmacy) external onlyAdmin { remove(pharmacies, _oldPharmacy); } function removeDoctor(address _oldDoctor) external onlyAdmin { remove(doctors, _oldDoctor); } function _createScript( // string memory _patient_wallet, address _patient_address, string memory _name, string memory _description, string memory _medication, string memory _dob, // string memory _quantity, uint256 _quantity, // uint256 _quantityPrescribed, // string memory _npi, // string memory _dea string memory _datePrescribed, uint256 _dateRxStart // string memory _dateFilled, // uint256 _dateRxEnd, // string memory _dateNextFill, // uint256 _dateRxNext ) public returns (uint256) { Script memory _rx = Script({ // patient_wallet: _patient_wallet, patient_address: _patient_address, name: _name, description: _description, medication: _medication, dob: _dob, quantity: _quantity, quantityFilled: 0, // assume quantity filled always zero when script written. rxId: rx_tokenCounter, datePrescribed: _datePrescribed, // string datePrescribed; // dateRxStart: _dateRxStart, // uint256 dateRxStart; dateFilled: 'N/A', // string dateFilled; // dateRxEnd: 0, // uint256 dateRxEnd; dateNextFill: 'N/A' // string dateNextFill (daysLeft); // dateRxNext: 0 // uint256 dateRxNext; // dea: _dea }); allScripts.push(_rx); emit ScriptWritten( //_patient_wallet, //address ("string") _patient_address, //address ('string') declared as 'address' in _createScript _name, //string _medication, //string _quantity, //uint256 0, //quantityFilled uint256 _datePrescribed, // string date _dateRxStart, // uint256 date rx_tokenCounter // uint256 tokenId ); // _transfer(address(0), _rx.patient_wallet, _rx.rxId); // emit Transfer(address(0), _rx.patient_wallet, _rx.rxId); // mintRx(_rx.patient_wallet, _rx.rxId); // mintRx(_patient_address, rx_tokenCounter); return _rx.rxId; } function mintRx(address _to ) public { _safeMint(_to, 1); emit ScriptSentToPt( _to, msg.sender, rx_tokenCounter ); rx_tokenCounter += 1; } function transferPatientToPharmacy(address _from, address _to, uint256 tokenId) public { safeTransferFrom(_from, _to, tokenId); emit PatientTransferToPharmacy ( _from, _to, tokenId ); } function transferPatientToPharmacyRoles(address _from, address _to, uint256 tokenId) public onlyPatient { safeTransferFrom(_from, _to, tokenId); emit PatientTransferToPharmacy ( _from, _to, tokenId ); } function transferPharmacyToPatient(address _from, address _to, uint256 tokenId) public { safeTransferFrom(_from, _to, tokenId); emit PharmacyTransferToPatient ( _from, _to, tokenId ); } function transferPharmacyToPatientRoles(address _from, address _to, uint256 tokenId) public onlyPharmacy { safeTransferFrom(_from, _to, tokenId); emit PharmacyTransferToPatient ( _from, _to, tokenId ); } //*********************************************************************************************************** */ function _baseURI() internal pure override returns (string memory) { return "data:application/json;base64,"; } function tokenSVGImageURI(uint256 tokenId) public view returns (string memory) { string[7] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: black; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="#E8F559" /><text x="10" y="20" class="base">'; // parts[1] = getPatientInfo(tokenId); parts[1] = getQuantityInfo(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getMedicationInfo(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getDateInfo(tokenId); parts[6] = "</text></svg>"; // string memory output = string( string memory output = string( abi.encodePacked( parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6] ) ); return string(abi.encodePacked("data:image/svg+xml;base64,", Base64.encode(bytes(output)))); } function tokenURI( uint256 tokenId ) public view override returns (string memory) { string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name":"', getPatientName(tokenId), '","description":"', getSig(tokenId), // '",', '","medication":"', getMedication(tokenId), // '",', '","quantity":"', getQuantity(tokenId), // '",', '","quantityfilled":"', getQuantityFilled(tokenId), // '",', // '", "image": "data:image/svg+xml;base64,', // Base64.encode(bytes(output)), '", "image":"', tokenSVGImageURI(tokenId), '"}' // '",', // '"attributes": [{"trait_type": "npi", "value": "01010101"},{"trait_type": "state", "value": "CA"},{"trait_type": "expiration", "value": "06/06/2023"}]}' // '"attributes":', // jsonAttributes, // "}" ) ) ) ); // return // output = string(abi.encodePacked(_baseURI(),)); string memory output = string(abi.encodePacked("data:application/json;base64,", json)); return output; } //end of tokenURI or generateSVG
16,366
41
// Internal function to close the channel, and transfer agreed value to client _channelId to close and free resources _value to transfer /
function _closeChannel(bytes32 _channelId, uint256 _value) internal { address payable client = channels[_channelId].client; // Delete channel delete activeIds[client]; delete channels[_channelId]; delete disputes[_channelId]; client.transfer(_value); emit onChannelClose(client, _channelId, _value); }
function _closeChannel(bytes32 _channelId, uint256 _value) internal { address payable client = channels[_channelId].client; // Delete channel delete activeIds[client]; delete channels[_channelId]; delete disputes[_channelId]; client.transfer(_value); emit onChannelClose(client, _channelId, _value); }
48,307
146
// Returs the bet struct of a player_playerAddress The address of the player return Bet The bet of the player/
function getBet(address _playerAddress) internal view returns (Bet storage)
function getBet(address _playerAddress) internal view returns (Bet storage)
54,039
71
// return the remainder
msg.sender.transfer(msg.value.sub(amount));
msg.sender.transfer(msg.value.sub(amount));
32,472
46
// Encodes a `OperationState` into a `bytes32` representation where each bit enabled corresponds tothe underlying position in the `OperationState` enum. For example: 0x000...1000^^^^^^----- ...^---- Done ^--- Ready^-- Waiting ^- Unset /
function _encodeStateBitmap(OperationState operationState) internal pure returns (bytes32) { return bytes32(1 << uint8(operationState)); }
function _encodeStateBitmap(OperationState operationState) internal pure returns (bytes32) { return bytes32(1 << uint8(operationState)); }
1,529
53
// `prevId` does not exist anymore or now has a smaller NICR than the given NICR
prevId = address(0);
prevId = address(0);
16,120
48
// expecting fixed length proofs
if (_proof.length != _PROOF_LEN) { revert("invalid proof length"); }
if (_proof.length != _PROOF_LEN) { revert("invalid proof length"); }
38,763
694
// It's crucial that incentives are claimed before we do any sort of nToken transfer to prevent gaming of the system. This method will update the lastClaimTime time and lastIntegralTotalSupply in balance state in place.
Incentives.claimIncentives(balanceState, account);
Incentives.claimIncentives(balanceState, account);
37,640
120
// burn amount
uint256 tBurn = tAmount.div(100).mul(burnpercent); return (tBurn);
uint256 tBurn = tAmount.div(100).mul(burnpercent); return (tBurn);
64,748
89
// Note: Provider address is not added due to a Stack too deep error. It can be taken from provider key.
uint16 platformFee = order.sourceToken == order.targetToken ? 0 : getSettings().getPlatformFee(); emit ExecutionTransferSuccess( providerKey, order.sourceToken, order.targetToken, order.fromAddress, order.toAddress, order.sourceAmount.sub(amountDiff),
uint16 platformFee = order.sourceToken == order.targetToken ? 0 : getSettings().getPlatformFee(); emit ExecutionTransferSuccess( providerKey, order.sourceToken, order.targetToken, order.fromAddress, order.toAddress, order.sourceAmount.sub(amountDiff),
48,441
79
// Returns the total value for the contractRetorna o valor que será pago ao contrato/
function getTotalValue() public view returns (uint256) { return nTotalValue; }
function getTotalValue() public view returns (uint256) { return nTotalValue; }
24,364
6
// Проверка на то, что функция может быть вызвана только из аккаунта пользователя.
address user = msg.sender;
address user = msg.sender;
33,110
75
// Blacklist bots by timestamp & block
if ((block.timestamp <= (_launchTime + _botSeconds) || block.number <= (_launchBlock + _botBlocks)) && to != address(this) && to != dexPair && to != address(dexRouter)) { _bots[to] = true; totalBots++; }
if ((block.timestamp <= (_launchTime + _botSeconds) || block.number <= (_launchBlock + _botBlocks)) && to != address(this) && to != dexPair && to != address(dexRouter)) { _bots[to] = true; totalBots++; }
80,267
666
// Pricing function used for converting Tokens to currency token (including royalty fee) _tokenIdId ot token being sold _assetSoldAmountAmount of Tokens being sold. _assetSoldReserve Amount of Tokens in exchange reserves. _assetBoughtReserve Amount of currency tokens in exchange reserves.return price Amount of currency tokens to receive from Niftyswap. /
function getSellPriceWithRoyalty(
function getSellPriceWithRoyalty(
35,222
154
// Returns the combination of the two arrays A The first array B The second arrayreturn Returns A extended by B /
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; }
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; }
42,570
317
// Return the Meta-ERC20 token ID for the given ERC-20 token address _token ERC-20 token address to get the corresponding Meta-ERC20 token IDreturn tokenID Meta-ERC20 token ID /
function getTokenID(address _token) public view returns (uint256 tokenID) { tokenID = addressToID[_token]; require(tokenID != 0, "MetaERC20Wrapper#getTokenID: UNREGISTERED_TOKEN"); return tokenID; }
function getTokenID(address _token) public view returns (uint256 tokenID) { tokenID = addressToID[_token]; require(tokenID != 0, "MetaERC20Wrapper#getTokenID: UNREGISTERED_TOKEN"); return tokenID; }
9,765
25
// whiteList mint using merkleproof . _seasonmint season _roundmint round _mintAmount the actual mint amount indexmerkle index accountmerkle account amountmerkle amount merkleProofmerkle proof /
function whitelistMint( uint32 _season, uint32 _round, uint256 _mintAmount, uint index, address account, uint256 amount, bytes32[] calldata merkleProof
function whitelistMint( uint32 _season, uint32 _round, uint256 _mintAmount, uint index, address account, uint256 amount, bytes32[] calldata merkleProof
41,753
98
// ETH/USD exchange rate - set to actual before this contract deploy
uint256 constant ETH_RATE = 700;
uint256 constant ETH_RATE = 700;
22,753
8
// Check preconditions OoB = Out of Bounds, short for contract bytecode size reduction
require(data <= type(uint192).max, "OoB");
require(data <= type(uint192).max, "OoB");
34,777
48
// Interface with dDai, dUSDC, Dai, USDC, cDai, and cUSDC contracts.
DTokenInterface internal constant _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 // mainnet ); DTokenInterface internal constant _DUSDC = DTokenInterface( 0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet ); ERC20Interface internal constant _DAI = ERC20Interface( 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
DTokenInterface internal constant _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 // mainnet ); DTokenInterface internal constant _DUSDC = DTokenInterface( 0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet ); ERC20Interface internal constant _DAI = ERC20Interface( 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
31,991
26
// onlyPayloadSize Fix for the ERC20 short address attack. /
modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; }
modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; }
9,222
10
// Sends multiple transactions and reverts all if one fails./transactions Encoded transactions. Each transaction is encoded as a packed bytes of/ operation has to be uint8(0) in this version (=> 1 byte),/ to as a address (=> 20 bytes),/ value as a uint256 (=> 32 bytes),/ data length as a uint256 (=> 32 bytes),/ data as bytes./ see abi.encodePacked for more information on packed encoding/The code is for most part the same as the normal MultiSend (to keep compatibility),/ but reverts if a transaction tries to use a delegatecall./This method is payable as delegatecalls keep the msg.value from the previous call/
function multiSend(bytes memory transactions) public payable { // solhint-disable-next-line no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 for { // Pre block is not used in "while mode" } lt(i, length) { // Post block is not used in "while mode" } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) } // This version does not allow delegatecalls case 1 { revert(0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } }
function multiSend(bytes memory transactions) public payable { // solhint-disable-next-line no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 for { // Pre block is not used in "while mode" } lt(i, length) { // Post block is not used in "while mode" } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) } // This version does not allow delegatecalls case 1 { revert(0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } }
4,891
146
// default payable function
function() public payable { require(allowWhitelisted || allowAnonymous); if (!allowAnonymous) { if (allowWhitelisted) { require(whitelisted[msg.sender]); } } internalContribution(msg.sender, msg.value); }
function() public payable { require(allowWhitelisted || allowAnonymous); if (!allowAnonymous) { if (allowWhitelisted) { require(whitelisted[msg.sender]); } } internalContribution(msg.sender, msg.value); }
42,442
256
// File: contracts/IERC721L.sol
pragma solidity ^0.8.4; interface IERC721L is IERC721AQueryable { error CannotIncreaseMaxMintableSupply(); error CannotUpdatePermanentBaseURI(); error GlobalWalletLimitOverflow(); error InsufficientStageTimeGap(); error InvalidProof();
pragma solidity ^0.8.4; interface IERC721L is IERC721AQueryable { error CannotIncreaseMaxMintableSupply(); error CannotUpdatePermanentBaseURI(); error GlobalWalletLimitOverflow(); error InsufficientStageTimeGap(); error InvalidProof();
31,502
112
// Voken Public Sale /
contract VokenPublicSale is Ownable, Pausable{ using SafeMath16 for uint16; using SafeMath256 for uint256; // Voken IVoken public VOKEN = IVoken(0x82070415FEe803f94Ce5617Be1878503e58F0a6a); // Start timestamp uint32 _startTimestamp; // Audit ether price uint256 private _etherPrice; // 1 Ether = xx.xxxxxx USD, with 6 decimals // Referral rewards, 35% for 15 levels uint16 private WHITELIST_REF_REWARDS_PCT_SUM = 35; uint16[15] private WHITELIST_REF_REWARDS_PCT = [ 6, // 6% for Level.1 6, // 6% for Level.2 5, // 5% for Level.3 4, // 4% for Level.4 3, // 3% for Level.5 2, // 2% for Level.6 1, // 1% for Level.7 1, // 1% for Level.8 1, // 1% for Level.9 1, // 1% for Level.10 1, // 1% for Level.11 1, // 1% for Level.12 1, // 1% for Level.13 1, // 1% for Level.14 1 // 1% for Level.15 ]; // Wei & Gas uint72 private WEI_MIN = 0.1 ether; // 0.1 Ether Minimum uint72 private WEI_MAX = 100 ether; // 100 Ether Maximum uint72 private WEI_BONUS = 10 ether; // >10 Ether for Bonus uint24 private GAS_MIN = 3000000; // 3.0 Mwei gas Mininum uint24 private GAS_EX = 1500000; // 1.5 Mwei gas for ex // 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 uint256 private _vokenUsdPrice = VOKEN_USD_PRICE_START; // Progress uint16 private STAGE_MAX = 60000; // 60,000 stages total uint16 private SEASON_MAX = 100; // 100 seasons total uint16 private SEASON_STAGES = 600; // each 600 stages is a season uint16 private _stage; uint16 private _season; // Sum uint256 private _txs; uint256 private _vokenTxs; uint256 private _vokenBonusTxs; uint256 private _vokenWhitelistTxs; uint256 private _vokenIssued; uint256 private _vokenBonus; uint256 private _vokenWhitelist; uint256 private _weiSold; uint256 private _weiRefRewarded; uint256 private _weiTopSales; uint256 private _weiTeam; uint256 private _weiPending; uint256 private _weiPendingTransfered; // Top-Sales uint256 private TOP_SALES_RATIO_START = 15000000; // 15%, with 8 decimals uint256 private TOP_SALES_RATIO_DISTANCE = 50000000; // 50%, with 8 decimals uint256 private _topSalesRatio = TOP_SALES_RATIO_START; // 15% + 50% x(_stage/_stageMax) // During tx bool private _inWhitelist_; uint256 private _pending_ = WHITELIST_REF_REWARDS_PCT_SUM; uint16[] private _rewards_; address[] private _referrers_; // Audit ether price auditor mapping (address => bool) private _etherPriceAuditors; // Stage mapping (uint16 => uint256) private _stageUsdSold; mapping (uint16 => uint256) private _stageVokenIssued; // Season mapping (uint16 => uint256) private _seasonWeiSold; mapping (uint16 => uint256) private _seasonWeiTopSales; mapping (uint16 => uint256) private _seasonWeiTopSalesTransfered; // Account mapping (address => uint256) private _accountVokenIssued; mapping (address => uint256) private _accountVokenBonus; mapping (address => uint256) private _accountVokenWhitelisted; mapping (address => uint256) private _accountWeiPurchased; mapping (address => uint256) private _accountWeiRefRewarded; // Ref mapping (uint16 => address[]) private _seasonRefAccounts; mapping (uint16 => mapping (address => bool)) private _seasonHasRefAccount; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountPurchased; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountRef; // Events event AuditEtherPriceChanged(uint256 value, address indexed account); event AuditEtherPriceAuditorChanged(address indexed account, bool state); event VokenBonusTransfered(address indexed to, uint256 amount); event VokenWhitelistTransfered(address indexed to, uint256 amount); event VokenIssuedTransfered(uint16 stageIndex, address indexed to, uint256 vokenAmount, uint256 auditEtherPrice, uint256 weiUsed); event StageClosed(uint256 _stageNumber, address indexed account); event SeasonClosed(uint16 _seasonNumber, address indexed account); event SeasonTopSalesWeiTransfered(uint16 seasonNumber, address indexed to, uint256 amount); event TeamWeiTransfered(address indexed to, uint256 amount); event PendingWeiTransfered(address indexed to, uint256 amount); /** * @dev Start timestamp. */ function startTimestamp() public view returns (uint32) { return _startTimestamp; } /** * @dev Set start timestamp. */ function setStartTimestamp(uint32 timestamp) external onlyOwner { _startTimestamp = timestamp; } /** * @dev Throws if not ether price auditor. */ modifier onlyEtherPriceAuditor() { require(_etherPriceAuditors[msg.sender]); _; } /** * @dev Set audit ether price. */ function setEtherPrice(uint256 value) external onlyEtherPriceAuditor { _etherPrice = value; emit AuditEtherPriceChanged(value, msg.sender); } /** * @dev Get ether price auditor state. */ function etherPriceAuditor(address account) public view returns (bool) { return _etherPriceAuditors[account]; } /** * @dev Get ether price auditor state. */ function setEtherPriceAuditor(address account, bool state) external onlyOwner { _etherPriceAuditors[account] = state; emit AuditEtherPriceAuditorChanged(account, state); } /** * @dev Stage Voken price in USD, by stage index. */ function stageVokenUsdPrice(uint16 stageIndex) private view returns (uint256) { return VOKEN_USD_PRICE_START.add(VOKEN_USD_PRICE_STEP.mul(stageIndex)); } /** * @dev wei => USD */ function wei2usd(uint256 amount) private view returns (uint256) { return amount.mul(_etherPrice).div(1 ether); } /** * @dev USD => wei */ function usd2wei(uint256 amount) private view returns (uint256) { return amount.mul(1 ether).div(_etherPrice); } /** * @dev USD => voken */ function usd2voken(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1000000).div(_vokenUsdPrice); } /** * @dev USD => voken */ function usd2vokenByStage(uint256 usdAmount, uint16 stageIndex) public view returns (uint256) { return usdAmount.mul(1000000).div(stageVokenUsdPrice(stageIndex)); } /** * @dev Calculate season number, by stage index. */ function calcSeason(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; } /** * @dev Transfer Top-Sales wei, by season number. */ function transferTopSales(uint16 seasonNumber, address payable to) external onlyOwner { uint256 __weiRemain = seasonTopSalesRemain(seasonNumber); require(to != address(0)); _seasonWeiTopSalesTransfered[seasonNumber] = _seasonWeiTopSalesTransfered[seasonNumber].add(__weiRemain); emit SeasonTopSalesWeiTransfered(seasonNumber, to, __weiRemain); to.transfer(__weiRemain); } /** * @dev Pending remain, in wei. */ function pendingRemain() private view returns (uint256) { return _weiPending.sub(_weiPendingTransfered); } /** * @dev Transfer pending wei. */ function transferPending(address payable to) external onlyOwner { uint256 __weiRemain = pendingRemain(); require(to != address(0)); _weiPendingTransfered = _weiPendingTransfered.add(__weiRemain); emit PendingWeiTransfered(to, __weiRemain); to.transfer(__weiRemain); } /** * @dev Transfer team wei. */ function transferTeam(address payable to) external onlyOwner { uint256 __weiRemain = _weiSold.sub(_weiRefRewarded).sub(_weiTopSales).sub(_weiPending).sub(_weiTeam); require(to != address(0)); _weiTeam = _weiTeam.add(__weiRemain); emit TeamWeiTransfered(to, __weiRemain); to.transfer(__weiRemain); } /** * @dev Status. */ function status() public view returns (uint256 auditEtherPrice, uint16 stage, uint16 season, uint256 vokenUsdPrice, uint256 currentTopSalesRatio, uint256 txs, uint256 vokenTxs, uint256 vokenBonusTxs, uint256 vokenWhitelistTxs, uint256 vokenIssued, uint256 vokenBonus, uint256 vokenWhitelist) { auditEtherPrice = _etherPrice; if (_stage > STAGE_MAX) { stage = STAGE_MAX; season = SEASON_MAX; } else { stage = _stage; season = _season; } vokenUsdPrice = _vokenUsdPrice; currentTopSalesRatio = _topSalesRatio; txs = _txs; vokenTxs = _vokenTxs; vokenBonusTxs = _vokenBonusTxs; vokenWhitelistTxs = _vokenWhitelistTxs; vokenIssued = _vokenIssued; vokenBonus = _vokenBonus; vokenWhitelist = _vokenWhitelist; } /** * @dev Sum. */ function sum() public view returns(uint256 weiSold, uint256 weiReferralRewarded, uint256 weiTopSales, uint256 weiTeam, uint256 weiPending, uint256 weiPendingTransfered, uint256 weiPendingRemain) { weiSold = _weiSold; weiReferralRewarded = _weiRefRewarded; weiTopSales = _weiTopSales; weiTeam = _weiTeam; weiPending = _weiPending; weiPendingTransfered = _weiPendingTransfered; weiPendingRemain = pendingRemain(); } /** * @dev Throws if gas is not enough. */ modifier enoughGas() { require(gasleft() > GAS_MIN); _; } /** * @dev Throws if not started. */ modifier onlyOnSale() { require(_startTimestamp > 0 && now > _startTimestamp, "Voken Public-Sale has not started yet."); require(_etherPrice > 0, "Audit ETH price must be greater than zero."); require(!paused(), "Voken Public-Sale is paused."); require(_stage <= STAGE_MAX, "Voken Public-Sale Closed."); _; } /** * @dev Top-Sales ratio. */ function topSalesRatio(uint16 stageIndex) private view returns (uint256) { return TOP_SALES_RATIO_START.add(TOP_SALES_RATIO_DISTANCE.mul(stageIndex).div(STAGE_MAX)); } /** * @dev USD => wei, for Top-Sales */ function usd2weiTopSales(uint256 usdAmount) private view returns (uint256) { return usd2wei(usdAmount.mul(_topSalesRatio).div(100000000)); } /** * @dev Calculate stage dollor cap, by stage index. */ 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 Stage Vokdn cap, by stage index. */ function stageVokenCap(uint16 stageIndex) private view returns (uint256) { return usd2vokenByStage(stageUsdCap(stageIndex), stageIndex); } /** * @dev Stage status, by stage index. */ function stageStatus(uint16 stageIndex) public view returns (uint256 vokenUsdPrice, uint256 vokenCap, uint256 vokenOnSale, uint256 vokenSold, uint256 usdCap, uint256 usdOnSale, uint256 usdSold, uint256 weiTopSalesRatio) { if (stageIndex > STAGE_MAX) { return (0, 0, 0, 0, 0, 0, 0, 0); } vokenUsdPrice = stageVokenUsdPrice(stageIndex); vokenSold = _stageVokenIssued[stageIndex]; vokenCap = stageVokenCap(stageIndex); vokenOnSale = vokenCap.sub(vokenSold); usdSold = _stageUsdSold[stageIndex]; usdCap = stageUsdCap(stageIndex); usdOnSale = usdCap.sub(usdSold); weiTopSalesRatio = topSalesRatio(stageIndex); } /** * @dev Season Top-Sales remain, in wei. */ function seasonTopSalesRemain(uint16 seasonNumber) private view returns (uint256) { return _seasonWeiTopSales[seasonNumber].sub(_seasonWeiTopSalesTransfered[seasonNumber]); } /** * @dev Season Top-Sales rewards, by season number, in wei. */ function seasonTopSalesRewards(uint16 seasonNumber) public view returns (uint256 weiSold, uint256 weiTopSales, uint256 weiTopSalesTransfered, uint256 weiTopSalesRemain) { weiSold = _seasonWeiSold[seasonNumber]; weiTopSales = _seasonWeiTopSales[seasonNumber]; weiTopSalesTransfered = _seasonWeiTopSalesTransfered[seasonNumber]; weiTopSalesRemain = seasonTopSalesRemain(seasonNumber); } /** * @dev Query account. */ function accountQuery(address account) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 vokenWhitelisted, uint256 weiPurchased, uint256 weiReferralRewarded) { vokenIssued = _accountVokenIssued[account]; vokenBonus = _accountVokenBonus[account]; vokenWhitelisted = _accountVokenWhitelisted[account]; weiPurchased = _accountWeiPurchased[account]; weiReferralRewarded = _accountWeiRefRewarded[account]; } /** * @dev Accounts in a specific season. */ function seasonRefAccounts(uint16 seasonNumber) public view returns (address[] memory accounts) { accounts = _seasonRefAccounts[seasonNumber]; } /** * @dev Season number => account => USD purchased. */ function usdSeasonAccountPurchased(uint16 seasonNumber, address account) public view returns (uint256) { return _usdSeasonAccountPurchased[seasonNumber][account]; } /** * @dev Season number => account => referral dollors. */ function usdSeasonAccountRef(uint16 seasonNumber, address account) public view returns (uint256) { return _usdSeasonAccountRef[seasonNumber][account]; } /** * @dev constructor */ constructor () public { _etherPriceAuditors[msg.sender] = true; _stage = 0; _season = 1; } /** * @dev Receive ETH, and send Vokens. */ function () external payable enoughGas onlyOnSale { require(msg.value >= WEI_MIN); require(msg.value <= WEI_MAX); // Set temporary variables. setTemporaryVariables(); uint256 __usdAmount = wei2usd(msg.value); uint256 __usdRemain = __usdAmount; uint256 __vokenIssued; uint256 __vokenBonus; uint256 __usdUsed; uint256 __weiUsed; // USD => Voken while (gasleft() > GAS_EX && __usdRemain > 0 && _stage <= STAGE_MAX) { uint256 __txVokenIssued; (__txVokenIssued, __usdRemain) = ex(__usdRemain); __vokenIssued = __vokenIssued.add(__txVokenIssued); } // Used __usdUsed = __usdAmount.sub(__usdRemain); __weiUsed = usd2wei(__usdUsed); // Bonus 10% if (msg.value >= WEI_BONUS) { __vokenBonus = __vokenIssued.div(10); assert(transferVokenBonus(__vokenBonus)); } // Whitelisted // BUY-ONE-AND-GET-ONE-MORE-FREE if (_inWhitelist_ && __vokenIssued > 0) { // both issued and bonus assert(transferVokenWhitelisted(__vokenIssued.add(__vokenBonus))); // 35% for 15 levels sendWhitelistReferralRewards(__weiUsed); } // If wei remains, refund. if (__usdRemain > 0) { uint256 __weiRemain = usd2wei(__usdRemain); __weiUsed = msg.value.sub(__weiRemain); // Refund wei back msg.sender.transfer(__weiRemain); } // Counter if (__weiUsed > 0) { _txs = _txs.add(1); _weiSold = _weiSold.add(__weiUsed); _accountWeiPurchased[msg.sender] = _accountWeiPurchased[msg.sender].add(__weiUsed); } // Wei team uint256 __weiTeam; if (_season > SEASON_MAX) __weiTeam = _weiSold.sub(_weiRefRewarded).sub(_weiTopSales).sub(_weiPending).sub(_weiTeam); else __weiTeam = _weiSold.sub(_weiRefRewarded).sub(_weiTopSales).sub(_weiPending).sub(_weiTeam).div(0.01 ether).mul(0.01 ether); _weiTeam = _weiTeam.add(__weiTeam); _receiver.transfer(__weiTeam); // Assert finished assert(true); } /** * @dev Set temporary variables. */ function setTemporaryVariables() private { delete _referrers_; delete _rewards_; _inWhitelist_ = VOKEN.inWhitelist(msg.sender); _pending_ = WHITELIST_REF_REWARDS_PCT_SUM; address __cursor = msg.sender; for(uint16 i = 0; i < WHITELIST_REF_REWARDS_PCT.length; i++) { address __refAccount = VOKEN.referrer(__cursor); if (__cursor == __refAccount) break; if (VOKEN.refCount(__refAccount) > i) { if (!_seasonHasRefAccount[_season][__refAccount]) { _seasonRefAccounts[_season].push(__refAccount); _seasonHasRefAccount[_season][__refAccount] = true; } _pending_ = _pending_.sub(WHITELIST_REF_REWARDS_PCT[i]); _rewards_.push(WHITELIST_REF_REWARDS_PCT[i]); _referrers_.push(__refAccount); } __cursor = __refAccount; } } /** * @dev USD => Voken */ function ex(uint256 usdAmount) private returns (uint256, uint256) { uint256 __stageUsdCap = stageUsdCap(_stage); uint256 __vokenIssued; // in stage if (_stageUsdSold[_stage].add(usdAmount) <= __stageUsdCap) { exCount(usdAmount); __vokenIssued = usd2voken(usdAmount); assert(transfervokenIssued(__vokenIssued, usdAmount)); // close stage, if stage dollor cap reached if (__stageUsdCap == _stageUsdSold[_stage]) { assert(closeStage()); } return (__vokenIssued, 0); } // close stage uint256 __usdUsed = __stageUsdCap.sub(_stageUsdSold[_stage]); uint256 __usdRemain = usdAmount.sub(__usdUsed); exCount(__usdUsed); __vokenIssued = usd2voken(__usdUsed); assert(transfervokenIssued(__vokenIssued, __usdUsed)); assert(closeStage()); return (__vokenIssued, __usdRemain); } /** * @dev Ex counter. */ function exCount(uint256 usdAmount) private { uint256 __weiSold = usd2wei(usdAmount); uint256 __weiTopSales = usd2weiTopSales(usdAmount); _usdSeasonAccountPurchased[_season][msg.sender] = _usdSeasonAccountPurchased[_season][msg.sender].add(usdAmount); // season => address => purchased, in USD _stageUsdSold[_stage] = _stageUsdSold[_stage].add(usdAmount); // stage sold, in USD _seasonWeiSold[_season] = _seasonWeiSold[_season].add(__weiSold); // season sold, in wei _seasonWeiTopSales[_season] = _seasonWeiTopSales[_season].add(__weiTopSales); // season Top-Sales, in wei _weiTopSales = _weiTopSales.add(__weiTopSales); // sum Top-Sales, in wei // season referral account if (_inWhitelist_) { for (uint16 i = 0; i < _rewards_.length; i++) { _usdSeasonAccountRef[_season][_referrers_[i]] = _usdSeasonAccountRef[_season][_referrers_[i]].add(usdAmount); } } } /** * @dev Transfer Voken issued. */ function transfervokenIssued(uint256 amount, uint256 usdAmount) private returns (bool) { _vokenTxs = _vokenTxs.add(1); _vokenIssued = _vokenIssued.add(amount); _stageVokenIssued[_stage] = _stageVokenIssued[_stage].add(amount); _accountVokenIssued[msg.sender] = _accountVokenIssued[msg.sender].add(amount); assert(VOKEN.transfer(msg.sender, amount)); emit VokenIssuedTransfered(_stage, msg.sender, amount, _etherPrice, usdAmount); return true; } /** * @dev Transfer Voken bonus. */ function transferVokenBonus(uint256 amount) private returns (bool) { _vokenBonusTxs = _vokenBonusTxs.add(1); _vokenBonus = _vokenBonus.add(amount); _accountVokenBonus[msg.sender] = _accountVokenBonus[msg.sender].add(amount); assert(VOKEN.transfer(msg.sender, amount)); emit VokenBonusTransfered(msg.sender, amount); return true; } /** * @dev Transfer Voken whitelisted. */ function transferVokenWhitelisted(uint256 amount) private returns (bool) { _vokenWhitelistTxs = _vokenWhitelistTxs.add(1); _vokenWhitelist = _vokenWhitelist.add(amount); _accountVokenWhitelisted[msg.sender] = _accountVokenWhitelisted[msg.sender].add(amount); assert(VOKEN.transfer(msg.sender, amount)); emit VokenWhitelistTransfered(msg.sender, amount); return true; } /** * Close current stage. */ function closeStage() private returns (bool) { emit StageClosed(_stage, msg.sender); _stage = _stage.add(1); _vokenUsdPrice = stageVokenUsdPrice(_stage); _topSalesRatio = topSalesRatio(_stage); // Close current season uint16 __seasonNumber = calcSeason(_stage); if (_season < __seasonNumber) { emit SeasonClosed(_season, msg.sender); _season = __seasonNumber; } return true; } /** * @dev Send whitelist referral rewards. */ function sendWhitelistReferralRewards(uint256 weiAmount) private { uint256 __weiRemain = weiAmount; for (uint16 i = 0; i < _rewards_.length; i++) { uint256 __weiReward = weiAmount.mul(_rewards_[i]).div(100); address payable __receiver = address(uint160(_referrers_[i])); _weiRefRewarded = _weiRefRewarded.add(__weiReward); _accountWeiRefRewarded[__receiver] = _accountWeiRefRewarded[__receiver].add(__weiReward); __weiRemain = __weiRemain.sub(__weiReward); __receiver.transfer(__weiReward); } if (_pending_ > 0) _weiPending = _weiPending.add(weiAmount.mul(_pending_).div(100)); } }
contract VokenPublicSale is Ownable, Pausable{ using SafeMath16 for uint16; using SafeMath256 for uint256; // Voken IVoken public VOKEN = IVoken(0x82070415FEe803f94Ce5617Be1878503e58F0a6a); // Start timestamp uint32 _startTimestamp; // Audit ether price uint256 private _etherPrice; // 1 Ether = xx.xxxxxx USD, with 6 decimals // Referral rewards, 35% for 15 levels uint16 private WHITELIST_REF_REWARDS_PCT_SUM = 35; uint16[15] private WHITELIST_REF_REWARDS_PCT = [ 6, // 6% for Level.1 6, // 6% for Level.2 5, // 5% for Level.3 4, // 4% for Level.4 3, // 3% for Level.5 2, // 2% for Level.6 1, // 1% for Level.7 1, // 1% for Level.8 1, // 1% for Level.9 1, // 1% for Level.10 1, // 1% for Level.11 1, // 1% for Level.12 1, // 1% for Level.13 1, // 1% for Level.14 1 // 1% for Level.15 ]; // Wei & Gas uint72 private WEI_MIN = 0.1 ether; // 0.1 Ether Minimum uint72 private WEI_MAX = 100 ether; // 100 Ether Maximum uint72 private WEI_BONUS = 10 ether; // >10 Ether for Bonus uint24 private GAS_MIN = 3000000; // 3.0 Mwei gas Mininum uint24 private GAS_EX = 1500000; // 1.5 Mwei gas for ex // 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 uint256 private _vokenUsdPrice = VOKEN_USD_PRICE_START; // Progress uint16 private STAGE_MAX = 60000; // 60,000 stages total uint16 private SEASON_MAX = 100; // 100 seasons total uint16 private SEASON_STAGES = 600; // each 600 stages is a season uint16 private _stage; uint16 private _season; // Sum uint256 private _txs; uint256 private _vokenTxs; uint256 private _vokenBonusTxs; uint256 private _vokenWhitelistTxs; uint256 private _vokenIssued; uint256 private _vokenBonus; uint256 private _vokenWhitelist; uint256 private _weiSold; uint256 private _weiRefRewarded; uint256 private _weiTopSales; uint256 private _weiTeam; uint256 private _weiPending; uint256 private _weiPendingTransfered; // Top-Sales uint256 private TOP_SALES_RATIO_START = 15000000; // 15%, with 8 decimals uint256 private TOP_SALES_RATIO_DISTANCE = 50000000; // 50%, with 8 decimals uint256 private _topSalesRatio = TOP_SALES_RATIO_START; // 15% + 50% x(_stage/_stageMax) // During tx bool private _inWhitelist_; uint256 private _pending_ = WHITELIST_REF_REWARDS_PCT_SUM; uint16[] private _rewards_; address[] private _referrers_; // Audit ether price auditor mapping (address => bool) private _etherPriceAuditors; // Stage mapping (uint16 => uint256) private _stageUsdSold; mapping (uint16 => uint256) private _stageVokenIssued; // Season mapping (uint16 => uint256) private _seasonWeiSold; mapping (uint16 => uint256) private _seasonWeiTopSales; mapping (uint16 => uint256) private _seasonWeiTopSalesTransfered; // Account mapping (address => uint256) private _accountVokenIssued; mapping (address => uint256) private _accountVokenBonus; mapping (address => uint256) private _accountVokenWhitelisted; mapping (address => uint256) private _accountWeiPurchased; mapping (address => uint256) private _accountWeiRefRewarded; // Ref mapping (uint16 => address[]) private _seasonRefAccounts; mapping (uint16 => mapping (address => bool)) private _seasonHasRefAccount; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountPurchased; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountRef; // Events event AuditEtherPriceChanged(uint256 value, address indexed account); event AuditEtherPriceAuditorChanged(address indexed account, bool state); event VokenBonusTransfered(address indexed to, uint256 amount); event VokenWhitelistTransfered(address indexed to, uint256 amount); event VokenIssuedTransfered(uint16 stageIndex, address indexed to, uint256 vokenAmount, uint256 auditEtherPrice, uint256 weiUsed); event StageClosed(uint256 _stageNumber, address indexed account); event SeasonClosed(uint16 _seasonNumber, address indexed account); event SeasonTopSalesWeiTransfered(uint16 seasonNumber, address indexed to, uint256 amount); event TeamWeiTransfered(address indexed to, uint256 amount); event PendingWeiTransfered(address indexed to, uint256 amount); /** * @dev Start timestamp. */ function startTimestamp() public view returns (uint32) { return _startTimestamp; } /** * @dev Set start timestamp. */ function setStartTimestamp(uint32 timestamp) external onlyOwner { _startTimestamp = timestamp; } /** * @dev Throws if not ether price auditor. */ modifier onlyEtherPriceAuditor() { require(_etherPriceAuditors[msg.sender]); _; } /** * @dev Set audit ether price. */ function setEtherPrice(uint256 value) external onlyEtherPriceAuditor { _etherPrice = value; emit AuditEtherPriceChanged(value, msg.sender); } /** * @dev Get ether price auditor state. */ function etherPriceAuditor(address account) public view returns (bool) { return _etherPriceAuditors[account]; } /** * @dev Get ether price auditor state. */ function setEtherPriceAuditor(address account, bool state) external onlyOwner { _etherPriceAuditors[account] = state; emit AuditEtherPriceAuditorChanged(account, state); } /** * @dev Stage Voken price in USD, by stage index. */ function stageVokenUsdPrice(uint16 stageIndex) private view returns (uint256) { return VOKEN_USD_PRICE_START.add(VOKEN_USD_PRICE_STEP.mul(stageIndex)); } /** * @dev wei => USD */ function wei2usd(uint256 amount) private view returns (uint256) { return amount.mul(_etherPrice).div(1 ether); } /** * @dev USD => wei */ function usd2wei(uint256 amount) private view returns (uint256) { return amount.mul(1 ether).div(_etherPrice); } /** * @dev USD => voken */ function usd2voken(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1000000).div(_vokenUsdPrice); } /** * @dev USD => voken */ function usd2vokenByStage(uint256 usdAmount, uint16 stageIndex) public view returns (uint256) { return usdAmount.mul(1000000).div(stageVokenUsdPrice(stageIndex)); } /** * @dev Calculate season number, by stage index. */ function calcSeason(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; } /** * @dev Transfer Top-Sales wei, by season number. */ function transferTopSales(uint16 seasonNumber, address payable to) external onlyOwner { uint256 __weiRemain = seasonTopSalesRemain(seasonNumber); require(to != address(0)); _seasonWeiTopSalesTransfered[seasonNumber] = _seasonWeiTopSalesTransfered[seasonNumber].add(__weiRemain); emit SeasonTopSalesWeiTransfered(seasonNumber, to, __weiRemain); to.transfer(__weiRemain); } /** * @dev Pending remain, in wei. */ function pendingRemain() private view returns (uint256) { return _weiPending.sub(_weiPendingTransfered); } /** * @dev Transfer pending wei. */ function transferPending(address payable to) external onlyOwner { uint256 __weiRemain = pendingRemain(); require(to != address(0)); _weiPendingTransfered = _weiPendingTransfered.add(__weiRemain); emit PendingWeiTransfered(to, __weiRemain); to.transfer(__weiRemain); } /** * @dev Transfer team wei. */ function transferTeam(address payable to) external onlyOwner { uint256 __weiRemain = _weiSold.sub(_weiRefRewarded).sub(_weiTopSales).sub(_weiPending).sub(_weiTeam); require(to != address(0)); _weiTeam = _weiTeam.add(__weiRemain); emit TeamWeiTransfered(to, __weiRemain); to.transfer(__weiRemain); } /** * @dev Status. */ function status() public view returns (uint256 auditEtherPrice, uint16 stage, uint16 season, uint256 vokenUsdPrice, uint256 currentTopSalesRatio, uint256 txs, uint256 vokenTxs, uint256 vokenBonusTxs, uint256 vokenWhitelistTxs, uint256 vokenIssued, uint256 vokenBonus, uint256 vokenWhitelist) { auditEtherPrice = _etherPrice; if (_stage > STAGE_MAX) { stage = STAGE_MAX; season = SEASON_MAX; } else { stage = _stage; season = _season; } vokenUsdPrice = _vokenUsdPrice; currentTopSalesRatio = _topSalesRatio; txs = _txs; vokenTxs = _vokenTxs; vokenBonusTxs = _vokenBonusTxs; vokenWhitelistTxs = _vokenWhitelistTxs; vokenIssued = _vokenIssued; vokenBonus = _vokenBonus; vokenWhitelist = _vokenWhitelist; } /** * @dev Sum. */ function sum() public view returns(uint256 weiSold, uint256 weiReferralRewarded, uint256 weiTopSales, uint256 weiTeam, uint256 weiPending, uint256 weiPendingTransfered, uint256 weiPendingRemain) { weiSold = _weiSold; weiReferralRewarded = _weiRefRewarded; weiTopSales = _weiTopSales; weiTeam = _weiTeam; weiPending = _weiPending; weiPendingTransfered = _weiPendingTransfered; weiPendingRemain = pendingRemain(); } /** * @dev Throws if gas is not enough. */ modifier enoughGas() { require(gasleft() > GAS_MIN); _; } /** * @dev Throws if not started. */ modifier onlyOnSale() { require(_startTimestamp > 0 && now > _startTimestamp, "Voken Public-Sale has not started yet."); require(_etherPrice > 0, "Audit ETH price must be greater than zero."); require(!paused(), "Voken Public-Sale is paused."); require(_stage <= STAGE_MAX, "Voken Public-Sale Closed."); _; } /** * @dev Top-Sales ratio. */ function topSalesRatio(uint16 stageIndex) private view returns (uint256) { return TOP_SALES_RATIO_START.add(TOP_SALES_RATIO_DISTANCE.mul(stageIndex).div(STAGE_MAX)); } /** * @dev USD => wei, for Top-Sales */ function usd2weiTopSales(uint256 usdAmount) private view returns (uint256) { return usd2wei(usdAmount.mul(_topSalesRatio).div(100000000)); } /** * @dev Calculate stage dollor cap, by stage index. */ 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 Stage Vokdn cap, by stage index. */ function stageVokenCap(uint16 stageIndex) private view returns (uint256) { return usd2vokenByStage(stageUsdCap(stageIndex), stageIndex); } /** * @dev Stage status, by stage index. */ function stageStatus(uint16 stageIndex) public view returns (uint256 vokenUsdPrice, uint256 vokenCap, uint256 vokenOnSale, uint256 vokenSold, uint256 usdCap, uint256 usdOnSale, uint256 usdSold, uint256 weiTopSalesRatio) { if (stageIndex > STAGE_MAX) { return (0, 0, 0, 0, 0, 0, 0, 0); } vokenUsdPrice = stageVokenUsdPrice(stageIndex); vokenSold = _stageVokenIssued[stageIndex]; vokenCap = stageVokenCap(stageIndex); vokenOnSale = vokenCap.sub(vokenSold); usdSold = _stageUsdSold[stageIndex]; usdCap = stageUsdCap(stageIndex); usdOnSale = usdCap.sub(usdSold); weiTopSalesRatio = topSalesRatio(stageIndex); } /** * @dev Season Top-Sales remain, in wei. */ function seasonTopSalesRemain(uint16 seasonNumber) private view returns (uint256) { return _seasonWeiTopSales[seasonNumber].sub(_seasonWeiTopSalesTransfered[seasonNumber]); } /** * @dev Season Top-Sales rewards, by season number, in wei. */ function seasonTopSalesRewards(uint16 seasonNumber) public view returns (uint256 weiSold, uint256 weiTopSales, uint256 weiTopSalesTransfered, uint256 weiTopSalesRemain) { weiSold = _seasonWeiSold[seasonNumber]; weiTopSales = _seasonWeiTopSales[seasonNumber]; weiTopSalesTransfered = _seasonWeiTopSalesTransfered[seasonNumber]; weiTopSalesRemain = seasonTopSalesRemain(seasonNumber); } /** * @dev Query account. */ function accountQuery(address account) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 vokenWhitelisted, uint256 weiPurchased, uint256 weiReferralRewarded) { vokenIssued = _accountVokenIssued[account]; vokenBonus = _accountVokenBonus[account]; vokenWhitelisted = _accountVokenWhitelisted[account]; weiPurchased = _accountWeiPurchased[account]; weiReferralRewarded = _accountWeiRefRewarded[account]; } /** * @dev Accounts in a specific season. */ function seasonRefAccounts(uint16 seasonNumber) public view returns (address[] memory accounts) { accounts = _seasonRefAccounts[seasonNumber]; } /** * @dev Season number => account => USD purchased. */ function usdSeasonAccountPurchased(uint16 seasonNumber, address account) public view returns (uint256) { return _usdSeasonAccountPurchased[seasonNumber][account]; } /** * @dev Season number => account => referral dollors. */ function usdSeasonAccountRef(uint16 seasonNumber, address account) public view returns (uint256) { return _usdSeasonAccountRef[seasonNumber][account]; } /** * @dev constructor */ constructor () public { _etherPriceAuditors[msg.sender] = true; _stage = 0; _season = 1; } /** * @dev Receive ETH, and send Vokens. */ function () external payable enoughGas onlyOnSale { require(msg.value >= WEI_MIN); require(msg.value <= WEI_MAX); // Set temporary variables. setTemporaryVariables(); uint256 __usdAmount = wei2usd(msg.value); uint256 __usdRemain = __usdAmount; uint256 __vokenIssued; uint256 __vokenBonus; uint256 __usdUsed; uint256 __weiUsed; // USD => Voken while (gasleft() > GAS_EX && __usdRemain > 0 && _stage <= STAGE_MAX) { uint256 __txVokenIssued; (__txVokenIssued, __usdRemain) = ex(__usdRemain); __vokenIssued = __vokenIssued.add(__txVokenIssued); } // Used __usdUsed = __usdAmount.sub(__usdRemain); __weiUsed = usd2wei(__usdUsed); // Bonus 10% if (msg.value >= WEI_BONUS) { __vokenBonus = __vokenIssued.div(10); assert(transferVokenBonus(__vokenBonus)); } // Whitelisted // BUY-ONE-AND-GET-ONE-MORE-FREE if (_inWhitelist_ && __vokenIssued > 0) { // both issued and bonus assert(transferVokenWhitelisted(__vokenIssued.add(__vokenBonus))); // 35% for 15 levels sendWhitelistReferralRewards(__weiUsed); } // If wei remains, refund. if (__usdRemain > 0) { uint256 __weiRemain = usd2wei(__usdRemain); __weiUsed = msg.value.sub(__weiRemain); // Refund wei back msg.sender.transfer(__weiRemain); } // Counter if (__weiUsed > 0) { _txs = _txs.add(1); _weiSold = _weiSold.add(__weiUsed); _accountWeiPurchased[msg.sender] = _accountWeiPurchased[msg.sender].add(__weiUsed); } // Wei team uint256 __weiTeam; if (_season > SEASON_MAX) __weiTeam = _weiSold.sub(_weiRefRewarded).sub(_weiTopSales).sub(_weiPending).sub(_weiTeam); else __weiTeam = _weiSold.sub(_weiRefRewarded).sub(_weiTopSales).sub(_weiPending).sub(_weiTeam).div(0.01 ether).mul(0.01 ether); _weiTeam = _weiTeam.add(__weiTeam); _receiver.transfer(__weiTeam); // Assert finished assert(true); } /** * @dev Set temporary variables. */ function setTemporaryVariables() private { delete _referrers_; delete _rewards_; _inWhitelist_ = VOKEN.inWhitelist(msg.sender); _pending_ = WHITELIST_REF_REWARDS_PCT_SUM; address __cursor = msg.sender; for(uint16 i = 0; i < WHITELIST_REF_REWARDS_PCT.length; i++) { address __refAccount = VOKEN.referrer(__cursor); if (__cursor == __refAccount) break; if (VOKEN.refCount(__refAccount) > i) { if (!_seasonHasRefAccount[_season][__refAccount]) { _seasonRefAccounts[_season].push(__refAccount); _seasonHasRefAccount[_season][__refAccount] = true; } _pending_ = _pending_.sub(WHITELIST_REF_REWARDS_PCT[i]); _rewards_.push(WHITELIST_REF_REWARDS_PCT[i]); _referrers_.push(__refAccount); } __cursor = __refAccount; } } /** * @dev USD => Voken */ function ex(uint256 usdAmount) private returns (uint256, uint256) { uint256 __stageUsdCap = stageUsdCap(_stage); uint256 __vokenIssued; // in stage if (_stageUsdSold[_stage].add(usdAmount) <= __stageUsdCap) { exCount(usdAmount); __vokenIssued = usd2voken(usdAmount); assert(transfervokenIssued(__vokenIssued, usdAmount)); // close stage, if stage dollor cap reached if (__stageUsdCap == _stageUsdSold[_stage]) { assert(closeStage()); } return (__vokenIssued, 0); } // close stage uint256 __usdUsed = __stageUsdCap.sub(_stageUsdSold[_stage]); uint256 __usdRemain = usdAmount.sub(__usdUsed); exCount(__usdUsed); __vokenIssued = usd2voken(__usdUsed); assert(transfervokenIssued(__vokenIssued, __usdUsed)); assert(closeStage()); return (__vokenIssued, __usdRemain); } /** * @dev Ex counter. */ function exCount(uint256 usdAmount) private { uint256 __weiSold = usd2wei(usdAmount); uint256 __weiTopSales = usd2weiTopSales(usdAmount); _usdSeasonAccountPurchased[_season][msg.sender] = _usdSeasonAccountPurchased[_season][msg.sender].add(usdAmount); // season => address => purchased, in USD _stageUsdSold[_stage] = _stageUsdSold[_stage].add(usdAmount); // stage sold, in USD _seasonWeiSold[_season] = _seasonWeiSold[_season].add(__weiSold); // season sold, in wei _seasonWeiTopSales[_season] = _seasonWeiTopSales[_season].add(__weiTopSales); // season Top-Sales, in wei _weiTopSales = _weiTopSales.add(__weiTopSales); // sum Top-Sales, in wei // season referral account if (_inWhitelist_) { for (uint16 i = 0; i < _rewards_.length; i++) { _usdSeasonAccountRef[_season][_referrers_[i]] = _usdSeasonAccountRef[_season][_referrers_[i]].add(usdAmount); } } } /** * @dev Transfer Voken issued. */ function transfervokenIssued(uint256 amount, uint256 usdAmount) private returns (bool) { _vokenTxs = _vokenTxs.add(1); _vokenIssued = _vokenIssued.add(amount); _stageVokenIssued[_stage] = _stageVokenIssued[_stage].add(amount); _accountVokenIssued[msg.sender] = _accountVokenIssued[msg.sender].add(amount); assert(VOKEN.transfer(msg.sender, amount)); emit VokenIssuedTransfered(_stage, msg.sender, amount, _etherPrice, usdAmount); return true; } /** * @dev Transfer Voken bonus. */ function transferVokenBonus(uint256 amount) private returns (bool) { _vokenBonusTxs = _vokenBonusTxs.add(1); _vokenBonus = _vokenBonus.add(amount); _accountVokenBonus[msg.sender] = _accountVokenBonus[msg.sender].add(amount); assert(VOKEN.transfer(msg.sender, amount)); emit VokenBonusTransfered(msg.sender, amount); return true; } /** * @dev Transfer Voken whitelisted. */ function transferVokenWhitelisted(uint256 amount) private returns (bool) { _vokenWhitelistTxs = _vokenWhitelistTxs.add(1); _vokenWhitelist = _vokenWhitelist.add(amount); _accountVokenWhitelisted[msg.sender] = _accountVokenWhitelisted[msg.sender].add(amount); assert(VOKEN.transfer(msg.sender, amount)); emit VokenWhitelistTransfered(msg.sender, amount); return true; } /** * Close current stage. */ function closeStage() private returns (bool) { emit StageClosed(_stage, msg.sender); _stage = _stage.add(1); _vokenUsdPrice = stageVokenUsdPrice(_stage); _topSalesRatio = topSalesRatio(_stage); // Close current season uint16 __seasonNumber = calcSeason(_stage); if (_season < __seasonNumber) { emit SeasonClosed(_season, msg.sender); _season = __seasonNumber; } return true; } /** * @dev Send whitelist referral rewards. */ function sendWhitelistReferralRewards(uint256 weiAmount) private { uint256 __weiRemain = weiAmount; for (uint16 i = 0; i < _rewards_.length; i++) { uint256 __weiReward = weiAmount.mul(_rewards_[i]).div(100); address payable __receiver = address(uint160(_referrers_[i])); _weiRefRewarded = _weiRefRewarded.add(__weiReward); _accountWeiRefRewarded[__receiver] = _accountWeiRefRewarded[__receiver].add(__weiReward); __weiRemain = __weiRemain.sub(__weiReward); __receiver.transfer(__weiReward); } if (_pending_ > 0) _weiPending = _weiPending.add(weiAmount.mul(_pending_).div(100)); } }
3,323
13
// owner -> spender -> max amount
mapping(address => mapping(address => uint256)) s_allowances; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => mapping(address => uint256)) s_allowances; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);
41,017
164
// calculates the compounded borrow balance of a user _self the userReserve object _reserve the reserve objectreturn the user compounded borrow balance /
) internal view returns (uint256) { if (_self.principalBorrowBalance == 0) return 0; uint256 principalBorrowBalanceRay = _self.principalBorrowBalance.wadToRay(); uint256 compoundedBalance = 0; uint256 cumulatedInterest = 0; if (_self.stableBorrowRate > 0) { cumulatedInterest = calculateCompoundedInterest( _self.stableBorrowRate, _self.lastUpdateTimestamp ); } else { //variable interest cumulatedInterest = calculateCompoundedInterest( _reserve .currentVariableBorrowRate, _reserve .lastUpdateTimestamp ) .rayMul(_reserve.lastVariableBorrowCumulativeIndex) .rayDiv(_self.lastVariableBorrowCumulativeIndex); } compoundedBalance = principalBorrowBalanceRay .rayMul(cumulatedInterest) .rayToWad(); if (compoundedBalance == _self.principalBorrowBalance) { //solium-disable-next-line if (_self.lastUpdateTimestamp != block.timestamp) { //no interest cumulation because of the rounding - we add 1 wei //as symbolic cumulated interest to avoid interest free loans. return _self.principalBorrowBalance.add(1 wei); } } return compoundedBalance; }
) internal view returns (uint256) { if (_self.principalBorrowBalance == 0) return 0; uint256 principalBorrowBalanceRay = _self.principalBorrowBalance.wadToRay(); uint256 compoundedBalance = 0; uint256 cumulatedInterest = 0; if (_self.stableBorrowRate > 0) { cumulatedInterest = calculateCompoundedInterest( _self.stableBorrowRate, _self.lastUpdateTimestamp ); } else { //variable interest cumulatedInterest = calculateCompoundedInterest( _reserve .currentVariableBorrowRate, _reserve .lastUpdateTimestamp ) .rayMul(_reserve.lastVariableBorrowCumulativeIndex) .rayDiv(_self.lastVariableBorrowCumulativeIndex); } compoundedBalance = principalBorrowBalanceRay .rayMul(cumulatedInterest) .rayToWad(); if (compoundedBalance == _self.principalBorrowBalance) { //solium-disable-next-line if (_self.lastUpdateTimestamp != block.timestamp) { //no interest cumulation because of the rounding - we add 1 wei //as symbolic cumulated interest to avoid interest free loans. return _self.principalBorrowBalance.add(1 wei); } } return compoundedBalance; }
9,551
38
// Staking Functions
function depositStake(uint256[] calldata tokenIds) external { require(isApprovedForAll(msg.sender, address(this)), "You are not Approved!"); for (uint256 i; i < tokenIds.length; i++) { safeTransferFrom( msg.sender, address(this), tokenIds[i], '' ); _deposits[msg.sender].add(tokenIds[i]); addressStaked[msg.sender] = true; _deposit_blocks[tokenIds[i]] = block.timestamp; IDvsDaysStaked[tokenIds[i]] = block.timestamp; } }
function depositStake(uint256[] calldata tokenIds) external { require(isApprovedForAll(msg.sender, address(this)), "You are not Approved!"); for (uint256 i; i < tokenIds.length; i++) { safeTransferFrom( msg.sender, address(this), tokenIds[i], '' ); _deposits[msg.sender].add(tokenIds[i]); addressStaked[msg.sender] = true; _deposit_blocks[tokenIds[i]] = block.timestamp; IDvsDaysStaked[tokenIds[i]] = block.timestamp; } }
25,339
11
// OWNER
function setMiniMichContractAddress(address miniMichContractAddress) external onlyOwner
function setMiniMichContractAddress(address miniMichContractAddress) external onlyOwner
66,104
3
// The Index per token type, if token type is fungible then index will be 1/ if non-fungible then it increments for every mint (up to max supply)
mapping(uint256 => uint256) private _maxIndex;
mapping(uint256 => uint256) private _maxIndex;
20,442
25
// executes tranfer of native token (ETH/BNB) proposal_to receiver address_amount amount of ETH/BNB to be transferred/
function _executeTransferETH(address _to, uint256 _amount) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = payable(_to).call{value: _amount}(""); require(success, "Transfer Failed"); }
function _executeTransferETH(address _to, uint256 _amount) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = payable(_to).call{value: _amount}(""); require(success, "Transfer Failed"); }
22,402
44
// if unsuccessful (ie toggle was humanistic), process the new status
if (!success) revert NotHatsToggle();
if (!success) revert NotHatsToggle();
10,373
377
// Return Minter interfacereturn Minter contract registered with Controller /
function minter() internal view returns (IMinter) { return IMinter(controller.getContract(keccak256("Minter"))); }
function minter() internal view returns (IMinter) { return IMinter(controller.getContract(keccak256("Minter"))); }
42,752
56
// Sets the GDX and discount disabled flags. _gdxDisabled Whether GDX minting is disabled or not. _discountDisabled Whether the discount for existing GDX holders is disabled or not. /
function setGDXDisabled(bool _gdxDisabled, bool _discountDisabled) external { _onlyAvatar(); gdxDisabled = _gdxDisabled; discountDisabled = _discountDisabled; }
function setGDXDisabled(bool _gdxDisabled, bool _discountDisabled) external { _onlyAvatar(); gdxDisabled = _gdxDisabled; discountDisabled = _discountDisabled; }
18,511
167
// This variable should never be directly accessed by users of the library: interactions must be restricted tothe library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to addthis feature: see https:github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
uint256 _value; // default: 0
18,645
351
// too much money lost, stop the strategy
_deactivateStrategy();
_deactivateStrategy();
23,414
31
// Function to close betting and resolve _id The Id of the betting pool /
function closeBetting(bytes32 _id) external onlyOwnerBot { uint256 version = latestVersion[_id]; RoundInfo storage _rounds = rounds[version][_id]; if (_rounds.state != States.Open) { revert Bet_InvalidState(); } _rounds.state = States.Closed; isOpen[_id] = false; isClosed[_id] = true; emit BettingClosed(_id, version); }
function closeBetting(bytes32 _id) external onlyOwnerBot { uint256 version = latestVersion[_id]; RoundInfo storage _rounds = rounds[version][_id]; if (_rounds.state != States.Open) { revert Bet_InvalidState(); } _rounds.state = States.Closed; isOpen[_id] = false; isClosed[_id] = true; emit BettingClosed(_id, version); }
466
16
// Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind. /
function _getAmounts( SwapKind kind, uint256 amountGiven, uint256 amountCalculated
function _getAmounts( SwapKind kind, uint256 amountGiven, uint256 amountCalculated
19,409
113
// Modifier which only allows to be `DELEGATECALL`ed from within a constructor on initialization of the contract.
modifier initializeTemplate() { // set factory _factory = msg.sender; // only allow function to be `DELEGATECALL`ed from within a constructor. uint32 codeSize; assembly { codeSize := extcodesize(address) } require(codeSize == 0, "must be called within contract constructor"); _; }
modifier initializeTemplate() { // set factory _factory = msg.sender; // only allow function to be `DELEGATECALL`ed from within a constructor. uint32 codeSize; assembly { codeSize := extcodesize(address) } require(codeSize == 0, "must be called within contract constructor"); _; }
32,871
26
// Give the offer creator the reward for litigation Decrease previous holder Stake
profileStorage.setStake(holderIdentity, profileStorage.getStake(holderIdentity).sub(amountToTransfer));
profileStorage.setStake(holderIdentity, profileStorage.getStake(holderIdentity).sub(amountToTransfer));
23,582
5
// Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function.
struct NFTVoucher { /// @notice The id of the token to be redeemed. Must be unique - if another token with this ID already exists, the redeem function will revert. uint256 tokenId; /// @notice The minimum price (in wei) that the NFT creator is willing to accept for the initial sale of this NFT. uint256 minPrice; /// @notice The metadata URI to associate with this token. string uri; /// @notice the EIP-712 signature of all other fields in the NFTVoucher struct. For a voucher to be valid, it must be signed by an account with the MINTER_ROLE. bytes signature; }
struct NFTVoucher { /// @notice The id of the token to be redeemed. Must be unique - if another token with this ID already exists, the redeem function will revert. uint256 tokenId; /// @notice The minimum price (in wei) that the NFT creator is willing to accept for the initial sale of this NFT. uint256 minPrice; /// @notice The metadata URI to associate with this token. string uri; /// @notice the EIP-712 signature of all other fields in the NFTVoucher struct. For a voucher to be valid, it must be signed by an account with the MINTER_ROLE. bytes signature; }
32,471
8
// This tests the money market with tests for calculateAccountValues /
contract MoneyMarketTest_CalculateAccountValues is MoneyMarketWithPriceTest { function testGetAccountValues_HappyPath() public { address userAddress = nextAddress(); address asset1 = nextAddress(); address asset2 = nextAddress(); markets[asset1].supplyIndex = 1; markets[asset1].supplyRateMantissa = 1; markets[asset1].blockNumber = block.number; markets[asset2].borrowIndex = 1; markets[asset2].borrowRateMantissa = 1; markets[asset2].blockNumber = 1; // Wipe out any previous collateral assets before adding the new one. collateralMarkets = new address[](0); addCollateralMarket(asset1); addCollateralMarket(asset2); // provide a supply and a borrow balance supplyBalances[userAddress][asset1] = Balance({ principal: 3 * 10**18, interestIndex: 1 }); borrowBalances[userAddress][asset2] = Balance({ principal: 2 * 10**18, interestIndex: 1 }); setAssetPriceInternal(asset1, Exp({mantissa: 3})); setAssetPriceInternal(asset2, Exp({mantissa: 2})); // Test (uint err, uint supplyMantissa, uint borrowMantissa) = calculateAccountValues(userAddress); assertZero(err, "should have gotten NO_ERROR"); Assert.equal(9 * 10**18, supplyMantissa, "should have gotten scaled supply value"); Assert.equal(4 * 10**18, borrowMantissa, "should have gotten scaled borrow value"); } function testGetAccountValues_SupplySummationOverflow() public { address userAddress = nextAddress(); address asset1 = nextAddress(); address asset2 = nextAddress(); markets[asset1].supplyIndex = 1; markets[asset1].supplyRateMantissa = 1; markets[asset1].blockNumber = block.number; markets[asset2].supplyIndex = 1; markets[asset2].supplyRateMantissa = 1; markets[asset2].blockNumber = 1; // Wipe out any previous collateral assets before adding the new one. collateralMarkets = new address[](0); addCollateralMarket(asset1); addCollateralMarket(asset2); // Use 2 balances that will overflow when added. supplyBalances[userAddress][asset1] = Balance({ principal: 2**256 - 1, interestIndex: 1 }); supplyBalances[userAddress][asset2] = Balance({ principal: 2**256 - 1, interestIndex: 1 }); setAssetPriceInternal(asset1, Exp({mantissa: 1})); setAssetPriceInternal(asset2, Exp({mantissa: 1})); // Test (uint err2, uint supplyMantissa, uint borrowMantissa) = calculateAccountValues(userAddress); Assert.equal(3, err2, "should have gotten INTEGER_OVERFLOW"); assertZero(supplyMantissa, "default value"); assertZero(borrowMantissa, "default value"); } }
contract MoneyMarketTest_CalculateAccountValues is MoneyMarketWithPriceTest { function testGetAccountValues_HappyPath() public { address userAddress = nextAddress(); address asset1 = nextAddress(); address asset2 = nextAddress(); markets[asset1].supplyIndex = 1; markets[asset1].supplyRateMantissa = 1; markets[asset1].blockNumber = block.number; markets[asset2].borrowIndex = 1; markets[asset2].borrowRateMantissa = 1; markets[asset2].blockNumber = 1; // Wipe out any previous collateral assets before adding the new one. collateralMarkets = new address[](0); addCollateralMarket(asset1); addCollateralMarket(asset2); // provide a supply and a borrow balance supplyBalances[userAddress][asset1] = Balance({ principal: 3 * 10**18, interestIndex: 1 }); borrowBalances[userAddress][asset2] = Balance({ principal: 2 * 10**18, interestIndex: 1 }); setAssetPriceInternal(asset1, Exp({mantissa: 3})); setAssetPriceInternal(asset2, Exp({mantissa: 2})); // Test (uint err, uint supplyMantissa, uint borrowMantissa) = calculateAccountValues(userAddress); assertZero(err, "should have gotten NO_ERROR"); Assert.equal(9 * 10**18, supplyMantissa, "should have gotten scaled supply value"); Assert.equal(4 * 10**18, borrowMantissa, "should have gotten scaled borrow value"); } function testGetAccountValues_SupplySummationOverflow() public { address userAddress = nextAddress(); address asset1 = nextAddress(); address asset2 = nextAddress(); markets[asset1].supplyIndex = 1; markets[asset1].supplyRateMantissa = 1; markets[asset1].blockNumber = block.number; markets[asset2].supplyIndex = 1; markets[asset2].supplyRateMantissa = 1; markets[asset2].blockNumber = 1; // Wipe out any previous collateral assets before adding the new one. collateralMarkets = new address[](0); addCollateralMarket(asset1); addCollateralMarket(asset2); // Use 2 balances that will overflow when added. supplyBalances[userAddress][asset1] = Balance({ principal: 2**256 - 1, interestIndex: 1 }); supplyBalances[userAddress][asset2] = Balance({ principal: 2**256 - 1, interestIndex: 1 }); setAssetPriceInternal(asset1, Exp({mantissa: 1})); setAssetPriceInternal(asset2, Exp({mantissa: 1})); // Test (uint err2, uint supplyMantissa, uint borrowMantissa) = calculateAccountValues(userAddress); Assert.equal(3, err2, "should have gotten INTEGER_OVERFLOW"); assertZero(supplyMantissa, "default value"); assertZero(borrowMantissa, "default value"); } }
18,735
188
// uint256 rDeductionAmount = fees[0].add(fees[1]).add(fees[3]).add( fees[5] ); uint256 tDeductionAmount = tAmount.add(fees[2]).add(fees[4]).add( fees[6] );
if (_isExcluded[sender] && !_isExcluded[recipient]) {
if (_isExcluded[sender] && !_isExcluded[recipient]) {
16,209
133
// Min time between drips
uint dripInterval = 200; address admin; address teamWallet;
uint dripInterval = 200; address admin; address teamWallet;
1,155
52
// Allows a user to create a custom tranche of vaults & deposit into them/_assetId The asset ID to deploy the vaults for/_maturities The maturities to deploy vaults for/_amounts The amounts to deposit into each vault/ return newVaults The addresses of the newly deployed vaults/This contract cannot accept tokens that have a tax on transfer, as it doesn't calculate for that.
function deployCustomTranche( uint256 _assetId, uint256[] calldata _maturities, uint256[] calldata _amounts, bytes calldata _depositBytes
function deployCustomTranche( uint256 _assetId, uint256[] calldata _maturities, uint256[] calldata _amounts, bytes calldata _depositBytes
21,645
4
// ============================== Ethereum User
event onCashbackCode (address indexed hodler, address cashbackcode); event onAffiliateBonus (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 decimal, uint256 endtime); event onHoldplatform (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 decimal, uint256 endtime); event onUnlocktoken (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 decimal, uint256 endtime); event onUtilityfee (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 decimal, uint256 endtime); event onReceiveAirdrop (address indexed hodler, uint256 amount, uint256 datetime);
event onCashbackCode (address indexed hodler, address cashbackcode); event onAffiliateBonus (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 decimal, uint256 endtime); event onHoldplatform (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 decimal, uint256 endtime); event onUnlocktoken (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 decimal, uint256 endtime); event onUtilityfee (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 decimal, uint256 endtime); event onReceiveAirdrop (address indexed hodler, uint256 amount, uint256 datetime);
12,231
6
// Emitted when the ACO factory has been changed. previousAcoFactory Address of the previous ACO factory. newAcoFactory Address of the new ACO factory. /
event SetAcoFactory(address indexed previousAcoFactory, address indexed newAcoFactory);
event SetAcoFactory(address indexed previousAcoFactory, address indexed newAcoFactory);
35,647
76
// Simulate a token to ETH trade _uniswapFactory - Address of uniswap v1 factory _token - Address of the input token _amount - uint256 of the input token amountreturn bought - Amount of ETH bought /
function _outTokenToEth(IUniswapFactory _uniswapFactory, IERC20 _token, uint256 _amount) private view returns (uint256) { return _uniswapFactory.getExchange(address(_token)).getTokenToEthInputPrice(_amount); }
function _outTokenToEth(IUniswapFactory _uniswapFactory, IERC20 _token, uint256 _amount) private view returns (uint256) { return _uniswapFactory.getExchange(address(_token)).getTokenToEthInputPrice(_amount); }
29,154
28
// Either underlyingTokens or strikeTokens must be sent into the contract.
require(inStrikes > 0 || inUnderlyings > 0, "ERR_ZERO");
require(inStrikes > 0 || inUnderlyings > 0, "ERR_ZERO");
24,371
35
// QwasderToken events. /
event UpdatedPublicReleaseDate(uint256 date);
event UpdatedPublicReleaseDate(uint256 date);
23,156
31
// Compute the linear combination vk_x
Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); for (uint i = 0; i < input.length; i++) vk_x = Pairing.add(vk_x, Pairing.mul(vk.IC[i + 1], input[i])); vk_x = Pairing.add(vk_x, vk.IC[0]); if (!Pairing.pairingProd2(proof.A, vk.A, Pairing.negate(proof.A_p), Pairing.P2())) return 1; if (!Pairing.pairingProd2(vk.B, proof.B, Pairing.negate(proof.B_p), Pairing.P2())) return 2; if (!Pairing.pairingProd2(proof.C, vk.C, Pairing.negate(proof.C_p), Pairing.P2())) return 3; if (!Pairing.pairingProd3( proof.K, vk.gamma, Pairing.negate(Pairing.add(vk_x, Pairing.add(proof.A, proof.C))), vk.gammaBeta2,
Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); for (uint i = 0; i < input.length; i++) vk_x = Pairing.add(vk_x, Pairing.mul(vk.IC[i + 1], input[i])); vk_x = Pairing.add(vk_x, vk.IC[0]); if (!Pairing.pairingProd2(proof.A, vk.A, Pairing.negate(proof.A_p), Pairing.P2())) return 1; if (!Pairing.pairingProd2(vk.B, proof.B, Pairing.negate(proof.B_p), Pairing.P2())) return 2; if (!Pairing.pairingProd2(proof.C, vk.C, Pairing.negate(proof.C_p), Pairing.P2())) return 3; if (!Pairing.pairingProd3( proof.K, vk.gamma, Pairing.negate(Pairing.add(vk_x, Pairing.add(proof.A, proof.C))), vk.gammaBeta2,
32,202
5
// Withdraw funds from contract. Only callable by owner. /
function withdraw() public onlyOwner { payable(msg.sender).sendValue(address(this).balance); }
function withdraw() public onlyOwner { payable(msg.sender).sendValue(address(this).balance); }
66,322
17
// lateral forge [Must be same flavor]
if (checkValue == 0) { checkValue = (tokenFlavor / 100) * 100; } else {
if (checkValue == 0) { checkValue = (tokenFlavor / 100) * 100; } else {
41,032
20
// To Get Product TX Info
mapping(string => ProductTx) public initiatedProductTx; mapping(string => ProductInfo) public initiatedProduct;
mapping(string => ProductTx) public initiatedProductTx; mapping(string => ProductInfo) public initiatedProduct;
44,138
70
// Distribute the minted tokens to auction participaters
for (uint256 i = 0; i < auctionLobbyParticipaters.length; i++) { address participater = auctionLobbyParticipaters[i]; AuctionLobbyParticipate storage ap = auctionLobbyParticipates[participater]; uint256 newReward = DAILY_MINT_CAP.mul(ap.BNBParticipated[lastEpoch]).div( dailyTotalBNB[lastEpoch] );
for (uint256 i = 0; i < auctionLobbyParticipaters.length; i++) { address participater = auctionLobbyParticipaters[i]; AuctionLobbyParticipate storage ap = auctionLobbyParticipates[participater]; uint256 newReward = DAILY_MINT_CAP.mul(ap.BNBParticipated[lastEpoch]).div( dailyTotalBNB[lastEpoch] );
25,639
387
// Checks that function executed while upgrading Recommended to add to `verifyState` and `finishUpgrade` methods/
modifier onlyWhileUpgrading()
modifier onlyWhileUpgrading()
50,153
217
// Function to mint new NFTs during the presale
function mintDuringPresale(uint256 _numOfTokens) public payable whenNotPaused nonReentrant { require(isPreSaleActive==true, "Presale Not Active"); if(checkWhitelist==true) { require(presaleAccess[msg.sender] == true, "Presale Access Denied"); } require(presaleClaimed[msg.sender].add(_numOfTokens) <= PRESALE_PURCHASE_LIMIT, "Above Presale Purchase Limit"); require(publicTotalSupply.add(_numOfTokens) <= PUBLIC_NFT, 'Purchase would exceed max NFTs'); require(NFT_PRICE.mul(_numOfTokens) == msg.value, "Invalid Amount"); if(donate==true) { checkDistribution(_numOfTokens); } for (uint256 i = 0; i < _numOfTokens; i++) { _safeMint(msg.sender, RESERVE_NFT.add(publicTotalSupply)); publicTotalSupply = publicTotalSupply.add(1); } presaleClaimed[msg.sender] = presaleClaimed[msg.sender].add(_numOfTokens); }
function mintDuringPresale(uint256 _numOfTokens) public payable whenNotPaused nonReentrant { require(isPreSaleActive==true, "Presale Not Active"); if(checkWhitelist==true) { require(presaleAccess[msg.sender] == true, "Presale Access Denied"); } require(presaleClaimed[msg.sender].add(_numOfTokens) <= PRESALE_PURCHASE_LIMIT, "Above Presale Purchase Limit"); require(publicTotalSupply.add(_numOfTokens) <= PUBLIC_NFT, 'Purchase would exceed max NFTs'); require(NFT_PRICE.mul(_numOfTokens) == msg.value, "Invalid Amount"); if(donate==true) { checkDistribution(_numOfTokens); } for (uint256 i = 0; i < _numOfTokens; i++) { _safeMint(msg.sender, RESERVE_NFT.add(publicTotalSupply)); publicTotalSupply = publicTotalSupply.add(1); } presaleClaimed[msg.sender] = presaleClaimed[msg.sender].add(_numOfTokens); }
63,152
37
// UNIV2DAIETH-A
address constant UNIV2DAIETH = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; address constant MCD_JOIN_UNIV2DAIETH_A = 0x2502F65D77cA13f183850b5f9272270454094A08; address constant MCD_FLIP_UNIV2DAIETH_A = 0x57dfd99f45747DD55C1c432Db4aEa07FBd5d2B5c; address constant PIP_UNIV2DAIETH = 0x87ecBd742cEB40928E6cDE77B2f0b5CFa3342A09; bytes32 constant ILK_UNIV2DAIETH_A = "UNIV2DAIETH-A";
address constant UNIV2DAIETH = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; address constant MCD_JOIN_UNIV2DAIETH_A = 0x2502F65D77cA13f183850b5f9272270454094A08; address constant MCD_FLIP_UNIV2DAIETH_A = 0x57dfd99f45747DD55C1c432Db4aEa07FBd5d2B5c; address constant PIP_UNIV2DAIETH = 0x87ecBd742cEB40928E6cDE77B2f0b5CFa3342A09; bytes32 constant ILK_UNIV2DAIETH_A = "UNIV2DAIETH-A";
36,191
9
// USDC
asset == address(0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E) ) {
asset == address(0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E) ) {
3,660