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
1
// Check if the caller's address matches the contract owner
require( msg.sender == owner, "Only the contract owner can call this function." );
require( msg.sender == owner, "Only the contract owner can call this function." );
19,559
459
// Computes the reward balance in ETH of the operator of a pool./poolId Unique id of pool./ return totalReward Balance in ETH.
function computeRewardBalanceOfOperator(bytes32 poolId) external view returns (uint256 reward);
function computeRewardBalanceOfOperator(bytes32 poolId) external view returns (uint256 reward);
12,372
35
// Deposits ERC20 token into DODO V1 Pool and stakes LP tokens to mine DODO. /
contract StrategyDODOV1 is AbstractStrategy { using SafeERC20 for IERC20; using Address for address; // The address of the DODO token address public immutable dodo; // The address of the USDT token address public immutable usdt; // The address of the DODO V1 pair / pool address public immutable dodoPairAddress; // The address of the DODO proxy address public immutable dodoProxy; // The address of the DODO mining pool address public immutable dodoMine; // The address of the DODO Approve contract address public immutable dodoApprove; // The address of the DODO V1 DODO-USDT pair address public immutable dodoV1_DODO_USDT_Pair; // The address of the Uniswap V2 router address public immutable uniV2Router; // Whether the supply token is the base token bool public immutable supplyBase; // The address of the DODO LP token for the pool address public immutable lpToken; uint256 public slippage = 2000; uint256 public constant SLIPPAGE_DENOMINATOR = 10000; uint256 public harvestThreshold = 50e18; constructor( address _supplyToken, address _dodo, address _usdt, address _dodoPair, address _dodoProxy, address _dodoMine, address _dodoApprove, address _dodoV1_DODO_USDT_Pair, address _uniV2Router, address _controller ) AbstractStrategy(_controller, _supplyToken) { dodo = _dodo; usdt = _usdt; dodoPairAddress = _dodoPair; dodoProxy = _dodoProxy; dodoMine = _dodoMine; dodoApprove = _dodoApprove; dodoV1_DODO_USDT_Pair = _dodoV1_DODO_USDT_Pair; uniV2Router = _uniV2Router; IDODOV1 dodoPair = IDODOV1(_dodoPair); bool _supplyBase = _supplyToken == IDODOV1(dodoPair)._BASE_TOKEN_(); supplyBase = _supplyBase; lpToken = _supplyBase ? dodoPair._BASE_CAPITAL_TOKEN_() : IDODOV1(dodoPair)._QUOTE_CAPITAL_TOKEN_(); } /** * @dev Require that the caller must be an EOA account to avoid flash loans. */ modifier onlyEOA() { require(msg.sender == tx.origin, "Not EOA"); _; } function getAssetAmount() public view override returns (uint256) { if (supplyToken == IDODOV1(dodoPairAddress)._BASE_TOKEN_()) { return getBaseAmount(); } return getQuoteAmount(); } function buy(uint256 _buyAmount) internal override returns (uint256) { uint256 originalAssetAmount = getAssetAmount(); // Pull supply token from Controller. IERC20(supplyToken).safeTransferFrom(msg.sender, address(this), _buyAmount); // Deposit supply token to the DODO pool. IDODOV1 dodoPair = IDODOV1(dodoPairAddress); IERC20(supplyToken).safeIncreaseAllowance(dodoPairAddress, _buyAmount); // TODO: Check price if (supplyBase) { dodoPair.depositBase(_buyAmount); } else { dodoPair.depositQuote(_buyAmount); } // Stake LP to earn DODO rewards uint256 lpBalance = IERC20(lpToken).balanceOf(address(this)); if (lpBalance > 0) { IERC20(lpToken).safeIncreaseAllowance(dodoMine, lpBalance); IDODOMine(dodoMine).deposit(lpToken, lpBalance); } uint256 newAssetAmount = getAssetAmount(); return newAssetAmount - originalAssetAmount; } function sell(uint256 _sellAmount) internal override returns (uint256) { uint256 balanceBeforeSell = IERC20(supplyToken).balanceOf(address(this)); // Unstake LP IDODOV1 dodoPair = IDODOV1(dodoPairAddress); (uint256 stakedLpAmount, ) = IDODOMine(dodoMine).userInfo(IDODOMine(dodoMine).getPid(lpToken), address(this)); IDODOMine(dodoMine).withdraw(lpToken, stakedLpAmount); // Withdraw supply token from the DODO pool. IDODOV1 dodoPool = IDODOV1(dodoPair); if (supplyBase) { dodoPool.withdrawBase(_sellAmount); } else { dodoPool.withdrawQuote(_sellAmount); } // Transfer supply token to Controller uint256 balanceAfterSell = IERC20(supplyToken).balanceOf(address(this)); IERC20(supplyToken).safeTransfer(msg.sender, balanceAfterSell); // Re-stake LP uint256 lpBalance = IERC20(lpToken).balanceOf(address(this)); if (lpBalance > 0) { IERC20(lpToken).safeIncreaseAllowance(dodoMine, lpBalance); IDODOMine(dodoMine).deposit(lpToken, lpBalance); } return balanceAfterSell - balanceBeforeSell; } function harvest() external override onlyEOA { // Sell DODO rewards to USDT on DODO's DODO-USDT pool, then sell the USDT on Uniswap V2 if necessary. IDODOMine(dodoMine).claim(lpToken); uint256 dodoBalance = IERC20(dodo).balanceOf(address(this)); if (dodoBalance < harvestThreshold) { return; } IERC20(dodo).safeIncreaseAllowance(dodoApprove, dodoBalance); address[] memory dodoV1Pairs = new address[](1); dodoV1Pairs[0] = dodoV1_DODO_USDT_Pair; // TODO: Check price IDODOV2Proxy01(dodoProxy).dodoSwapV1(dodo, usdt, dodoBalance, 1, dodoV1Pairs, 0, false, block.timestamp + 1800); uint256 usdtBalance = IERC20(usdt).balanceOf(address(this)); if (supplyToken != usdt) { address[] memory paths = new address[](2); paths[0] = usdt; paths[1] = supplyToken; IERC20(usdt).safeIncreaseAllowance(uniV2Router, usdtBalance); // TODO: Check price IUniswapV2Router02(uniV2Router).swapExactTokensForTokens( usdtBalance, 0, paths, address(this), block.timestamp + 1800 ); } // Deposit supply token to the DODO pool. uint256 supplyTokenBalance = IERC20(supplyToken).balanceOf(address(this)); IDODOV1 dodoPair = IDODOV1(dodoPairAddress); IERC20(supplyToken).safeIncreaseAllowance(dodoPairAddress, supplyTokenBalance); // TODO: Check price if (supplyBase) { dodoPair.depositBase(supplyTokenBalance); } else { dodoPair.depositQuote(supplyTokenBalance); } // Stake LP to earn DODO rewards uint256 lpBalance = IERC20(lpToken).balanceOf(address(this)); if (lpBalance > 0) { IERC20(lpToken).safeIncreaseAllowance(dodoMine, lpBalance); IDODOMine(dodoMine).deposit(lpToken, lpBalance); } } function getBaseAmount() public view returns (uint256) { IDODOV1 dodoPair = IDODOV1(dodoPairAddress); uint256 totalBaseCapital = dodoPair.getTotalBaseCapital(); if (totalBaseCapital == 0) { return 0; } (uint256 baseTarget, ) = dodoPair.getExpectedTarget(); (uint256 stakedLpAmount, ) = IDODOMine(dodoMine).userInfo(IDODOMine(dodoMine).getPid(lpToken), address(this)); return ((stakedLpAmount + dodoPair.getBaseCapitalBalanceOf(address(this))) * baseTarget) / totalBaseCapital; } function getQuoteAmount() public view returns (uint256) { IDODOV1 dodoPair = IDODOV1(dodoPairAddress); uint256 totalQuoteCapital = dodoPair.getTotalQuoteCapital(); if (totalQuoteCapital == 0) { return 0; } (, uint256 quoteTarget) = dodoPair.getExpectedTarget(); (uint256 stakedLpAmount, ) = IDODOMine(dodoMine).userInfo(IDODOMine(dodoMine).getPid(lpToken), address(this)); return ((stakedLpAmount + dodoPair.getQuoteCapitalBalanceOf(address(this))) * quoteTarget) / totalQuoteCapital; } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = lpToken; protected[1] = dodo; return protected; } function setSlippage(uint256 _slippage) external onlyOwner { slippage = _slippage; } function setHarvestThreshold(uint256 _harvestThreshold) external onlyOwner { harvestThreshold = _harvestThreshold; } }
contract StrategyDODOV1 is AbstractStrategy { using SafeERC20 for IERC20; using Address for address; // The address of the DODO token address public immutable dodo; // The address of the USDT token address public immutable usdt; // The address of the DODO V1 pair / pool address public immutable dodoPairAddress; // The address of the DODO proxy address public immutable dodoProxy; // The address of the DODO mining pool address public immutable dodoMine; // The address of the DODO Approve contract address public immutable dodoApprove; // The address of the DODO V1 DODO-USDT pair address public immutable dodoV1_DODO_USDT_Pair; // The address of the Uniswap V2 router address public immutable uniV2Router; // Whether the supply token is the base token bool public immutable supplyBase; // The address of the DODO LP token for the pool address public immutable lpToken; uint256 public slippage = 2000; uint256 public constant SLIPPAGE_DENOMINATOR = 10000; uint256 public harvestThreshold = 50e18; constructor( address _supplyToken, address _dodo, address _usdt, address _dodoPair, address _dodoProxy, address _dodoMine, address _dodoApprove, address _dodoV1_DODO_USDT_Pair, address _uniV2Router, address _controller ) AbstractStrategy(_controller, _supplyToken) { dodo = _dodo; usdt = _usdt; dodoPairAddress = _dodoPair; dodoProxy = _dodoProxy; dodoMine = _dodoMine; dodoApprove = _dodoApprove; dodoV1_DODO_USDT_Pair = _dodoV1_DODO_USDT_Pair; uniV2Router = _uniV2Router; IDODOV1 dodoPair = IDODOV1(_dodoPair); bool _supplyBase = _supplyToken == IDODOV1(dodoPair)._BASE_TOKEN_(); supplyBase = _supplyBase; lpToken = _supplyBase ? dodoPair._BASE_CAPITAL_TOKEN_() : IDODOV1(dodoPair)._QUOTE_CAPITAL_TOKEN_(); } /** * @dev Require that the caller must be an EOA account to avoid flash loans. */ modifier onlyEOA() { require(msg.sender == tx.origin, "Not EOA"); _; } function getAssetAmount() public view override returns (uint256) { if (supplyToken == IDODOV1(dodoPairAddress)._BASE_TOKEN_()) { return getBaseAmount(); } return getQuoteAmount(); } function buy(uint256 _buyAmount) internal override returns (uint256) { uint256 originalAssetAmount = getAssetAmount(); // Pull supply token from Controller. IERC20(supplyToken).safeTransferFrom(msg.sender, address(this), _buyAmount); // Deposit supply token to the DODO pool. IDODOV1 dodoPair = IDODOV1(dodoPairAddress); IERC20(supplyToken).safeIncreaseAllowance(dodoPairAddress, _buyAmount); // TODO: Check price if (supplyBase) { dodoPair.depositBase(_buyAmount); } else { dodoPair.depositQuote(_buyAmount); } // Stake LP to earn DODO rewards uint256 lpBalance = IERC20(lpToken).balanceOf(address(this)); if (lpBalance > 0) { IERC20(lpToken).safeIncreaseAllowance(dodoMine, lpBalance); IDODOMine(dodoMine).deposit(lpToken, lpBalance); } uint256 newAssetAmount = getAssetAmount(); return newAssetAmount - originalAssetAmount; } function sell(uint256 _sellAmount) internal override returns (uint256) { uint256 balanceBeforeSell = IERC20(supplyToken).balanceOf(address(this)); // Unstake LP IDODOV1 dodoPair = IDODOV1(dodoPairAddress); (uint256 stakedLpAmount, ) = IDODOMine(dodoMine).userInfo(IDODOMine(dodoMine).getPid(lpToken), address(this)); IDODOMine(dodoMine).withdraw(lpToken, stakedLpAmount); // Withdraw supply token from the DODO pool. IDODOV1 dodoPool = IDODOV1(dodoPair); if (supplyBase) { dodoPool.withdrawBase(_sellAmount); } else { dodoPool.withdrawQuote(_sellAmount); } // Transfer supply token to Controller uint256 balanceAfterSell = IERC20(supplyToken).balanceOf(address(this)); IERC20(supplyToken).safeTransfer(msg.sender, balanceAfterSell); // Re-stake LP uint256 lpBalance = IERC20(lpToken).balanceOf(address(this)); if (lpBalance > 0) { IERC20(lpToken).safeIncreaseAllowance(dodoMine, lpBalance); IDODOMine(dodoMine).deposit(lpToken, lpBalance); } return balanceAfterSell - balanceBeforeSell; } function harvest() external override onlyEOA { // Sell DODO rewards to USDT on DODO's DODO-USDT pool, then sell the USDT on Uniswap V2 if necessary. IDODOMine(dodoMine).claim(lpToken); uint256 dodoBalance = IERC20(dodo).balanceOf(address(this)); if (dodoBalance < harvestThreshold) { return; } IERC20(dodo).safeIncreaseAllowance(dodoApprove, dodoBalance); address[] memory dodoV1Pairs = new address[](1); dodoV1Pairs[0] = dodoV1_DODO_USDT_Pair; // TODO: Check price IDODOV2Proxy01(dodoProxy).dodoSwapV1(dodo, usdt, dodoBalance, 1, dodoV1Pairs, 0, false, block.timestamp + 1800); uint256 usdtBalance = IERC20(usdt).balanceOf(address(this)); if (supplyToken != usdt) { address[] memory paths = new address[](2); paths[0] = usdt; paths[1] = supplyToken; IERC20(usdt).safeIncreaseAllowance(uniV2Router, usdtBalance); // TODO: Check price IUniswapV2Router02(uniV2Router).swapExactTokensForTokens( usdtBalance, 0, paths, address(this), block.timestamp + 1800 ); } // Deposit supply token to the DODO pool. uint256 supplyTokenBalance = IERC20(supplyToken).balanceOf(address(this)); IDODOV1 dodoPair = IDODOV1(dodoPairAddress); IERC20(supplyToken).safeIncreaseAllowance(dodoPairAddress, supplyTokenBalance); // TODO: Check price if (supplyBase) { dodoPair.depositBase(supplyTokenBalance); } else { dodoPair.depositQuote(supplyTokenBalance); } // Stake LP to earn DODO rewards uint256 lpBalance = IERC20(lpToken).balanceOf(address(this)); if (lpBalance > 0) { IERC20(lpToken).safeIncreaseAllowance(dodoMine, lpBalance); IDODOMine(dodoMine).deposit(lpToken, lpBalance); } } function getBaseAmount() public view returns (uint256) { IDODOV1 dodoPair = IDODOV1(dodoPairAddress); uint256 totalBaseCapital = dodoPair.getTotalBaseCapital(); if (totalBaseCapital == 0) { return 0; } (uint256 baseTarget, ) = dodoPair.getExpectedTarget(); (uint256 stakedLpAmount, ) = IDODOMine(dodoMine).userInfo(IDODOMine(dodoMine).getPid(lpToken), address(this)); return ((stakedLpAmount + dodoPair.getBaseCapitalBalanceOf(address(this))) * baseTarget) / totalBaseCapital; } function getQuoteAmount() public view returns (uint256) { IDODOV1 dodoPair = IDODOV1(dodoPairAddress); uint256 totalQuoteCapital = dodoPair.getTotalQuoteCapital(); if (totalQuoteCapital == 0) { return 0; } (, uint256 quoteTarget) = dodoPair.getExpectedTarget(); (uint256 stakedLpAmount, ) = IDODOMine(dodoMine).userInfo(IDODOMine(dodoMine).getPid(lpToken), address(this)); return ((stakedLpAmount + dodoPair.getQuoteCapitalBalanceOf(address(this))) * quoteTarget) / totalQuoteCapital; } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = lpToken; protected[1] = dodo; return protected; } function setSlippage(uint256 _slippage) external onlyOwner { slippage = _slippage; } function setHarvestThreshold(uint256 _harvestThreshold) external onlyOwner { harvestThreshold = _harvestThreshold; } }
28,607
0
// address public token = 0xaD6D458402F60fD3Bd25163575031ACDce07538D;ropDAI (testing)
ERC20 erc20 = ERC20(token); address public owner = 0x7ab874Eeef0169ADA0d225E9801A3FfFfa26aAC3; // me mapping (address => bool) public pumpers; uint public lastPumpTime = 0; uint public interval = 60*60*24*7; // one week intervals uint public flowRate = 1; // dispense 1% each time uint public flowGuage = 100;
ERC20 erc20 = ERC20(token); address public owner = 0x7ab874Eeef0169ADA0d225E9801A3FfFfa26aAC3; // me mapping (address => bool) public pumpers; uint public lastPumpTime = 0; uint public interval = 60*60*24*7; // one week intervals uint public flowRate = 1; // dispense 1% each time uint public flowGuage = 100;
42,172
251
// Initialize the core with an initial node initialNode Initial node to start the chain with /
function initializeCore(INode initialNode) internal { _nodes[0] = initialNode; _firstUnresolvedNode = 1; }
function initializeCore(INode initialNode) internal { _nodes[0] = initialNode; _firstUnresolvedNode = 1; }
35,840
0
// Interface to ZBR ICO Contract
contract DaoToken { uint256 public CAP; uint256 public totalEthers; function proxyPayment(address participant) payable; function transfer(address _to, uint _amount) returns (bool success); }
contract DaoToken { uint256 public CAP; uint256 public totalEthers; function proxyPayment(address participant) payable; function transfer(address _to, uint _amount) returns (bool success); }
13,101
174
// ERC20 token with pausable token transfers, minting and burning. Useful for scenarios such as preventing trades until the end of an evaluationperiod, or having an emergency switch for freezing all token transfers in theevent of a large bug. /
abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } }
abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } }
3,664
44
// Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. /
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
4,403
260
// current rate per token - rate user previously received
uint256 userRewardDelta = _currentRewardPerToken - userData[_account].rewardPerTokenPaid; // + 1 SLOAD
uint256 userRewardDelta = _currentRewardPerToken - userData[_account].rewardPerTokenPaid; // + 1 SLOAD
57,980
64
// storemantx info
struct SmgTx { BaseTx baseTx; uint tokenPairID; uint value; address userAccount; /// HTLC transaction user address for the security check while user's redeem }
struct SmgTx { BaseTx baseTx; uint tokenPairID; uint value; address userAccount; /// HTLC transaction user address for the security check while user's redeem }
39,251
3
// Instead of storing all data required to execute an action in storage, we only save the hash to make action creation cheaper. The hash is computed by taking the keccak256 hash of the concatenation of each field in the `ActionInfo` struct.
bytes32 infoHash; bool executed; // Has action executed. bool canceled; // Is action canceled. bool isScript; // Is the action's target a script. ILlamaActionGuard guard; // The action's guard. This is the address(0) if no guard is set on the action's target and
bytes32 infoHash; bool executed; // Has action executed. bool canceled; // Is action canceled. bool isScript; // Is the action's target a script. ILlamaActionGuard guard; // The action's guard. This is the address(0) if no guard is set on the action's target and
33,925
53
// See {BEP20-approve}. Requirements: - `spender` cannot be the zero address. /
function approve(address spender, uint256 amount) override external returns (bool) { _approve(_msgSender(), spender, amount); return true; }
function approve(address spender, uint256 amount) override external returns (bool) { _approve(_msgSender(), spender, amount); return true; }
30,817
9
// Buy busd with 0.5% slippage
uint256 amount = SwapUtils.swapExactETHForTokens(router, busd, weiAmount, swapSlippage); // no checks required for this? uint256 tokens = _getTokenAmount(amount); _preValidatePurchase(beneficiary, amount, tokens); _processPurchase(beneficiary, amount, tokens); emit TokensPurchased(_msgSender(), beneficiary, amount, tokens);
uint256 amount = SwapUtils.swapExactETHForTokens(router, busd, weiAmount, swapSlippage); // no checks required for this? uint256 tokens = _getTokenAmount(amount); _preValidatePurchase(beneficiary, amount, tokens); _processPurchase(beneficiary, amount, tokens); emit TokensPurchased(_msgSender(), beneficiary, amount, tokens);
12,674
20
// Add an airline to the registration queueCan only be called from FlightSuretyApp contract/
function registerAirline ( address callingAirline, address newAirline ) external requireIsOperational() isAuthorizedCaller() requirePaidFund(callingAirline) returns (bool result)
function registerAirline ( address callingAirline, address newAirline ) external requireIsOperational() isAuthorizedCaller() requirePaidFund(callingAirline) returns (bool result)
2,407
106
// Deposit multiple tokens to the vault. Quantities should be in theorder of the addresses of the tokens being deposited. _tokens Array of the addresses of the ERC20 tokens_quantities Array of the number of tokens to deposit /
function batchDeposit(
function batchDeposit(
42,528
16
// Ownable constructor ตั้งค่าบัญชีของ sender ให้เป็น `owner` ดั้งเดิมของ contract /
constructor() public { owner = msg.sender; owners[msg.sender] = true; }
constructor() public { owner = msg.sender; owners[msg.sender] = true; }
47,518
59
// y = mx + b = paymentSlope(x - x0) + y0 divide by precision factor here since we have completed the rounding error sensitive operations
totalCoins = (paymentSlope * (vestingTime - tree.minEndTime) / PRECISION) + minTotalPayments;
totalCoins = (paymentSlope * (vestingTime - tree.minEndTime) / PRECISION) + minTotalPayments;
52,382
99
// _tokens: The number of tokens to be bought. This function executes the buy of tokens from a user. This was done for readability. This function can only be called internally./
function _executeBuy(uint _tokens) internal { uint256 cost = getBuyCost(_tokens); require( collateralInstance.allowance( msg.sender, address(this) ) >= cost, "User has not approved contract for token cost amount" ); require( collateralInstance.transferFrom( msg.sender, address(this), cost ), "Transfering of collateral failed" ); _mint(msg.sender, _tokens); }
function _executeBuy(uint _tokens) internal { uint256 cost = getBuyCost(_tokens); require( collateralInstance.allowance( msg.sender, address(this) ) >= cost, "User has not approved contract for token cost amount" ); require( collateralInstance.transferFrom( msg.sender, address(this), cost ), "Transfering of collateral failed" ); _mint(msg.sender, _tokens); }
2,126
88
// Call tell() on RWALiquidationOracle
RwaLiquidationOracleLike_1(MIP21_LIQUIDATION_ORACLE).tell("RWA003-A");
RwaLiquidationOracleLike_1(MIP21_LIQUIDATION_ORACLE).tell("RWA003-A");
30,283
81
// Gets the total amount of tokens stored by the contract. return uint256 representing the total amount of tokens/
function totalSupply() public view returns (uint256) { return _allTokens.length; }
function totalSupply() public view returns (uint256) { return _allTokens.length; }
45,995
105
// NOTE: We don't use SafeMath (or similar) in this function becauseall of our entry functions carefully cap the maximum values forcurrency (at 128-bits), and ownerCut <= 10000 (see the require()statement in the ClockAuction constructor). The result of thisfunction is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
return _price * ownerCut / 10000;
7,580
7
// require a new name, the address of the name must be 0x0 (otherwise, means duplicate name).
require(nameToAddr[_name] == address(0), "this name has been used.");
require(nameToAddr[_name] == address(0), "this name has been used.");
1,969
42
// Calculate reduction in y if D = d1
uint y0 = _getYD(i, xp, d1);
uint y0 = _getYD(i, xp, d1);
37,775
88
// use the index to determine the node ordering (index ranges 1 to n)
bytes32 element; bytes32 hash = leaf; uint remaining;
bytes32 element; bytes32 hash = leaf; uint remaining;
24,255
134
// indexed events are emitted
emit BondCreated( _amount, payout, block.number.add(terms.vestingTerm), priceInUSD ); emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio()); adjust(); // control variable is adjusted return payout;
emit BondCreated( _amount, payout, block.number.add(terms.vestingTerm), priceInUSD ); emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio()); adjust(); // control variable is adjusted return payout;
15,998
56
// Execute spin.
function _spinTokens(TKN _tkn, uint divRate) private betIsValid(_tkn.value, divRate)
function _spinTokens(TKN _tkn, uint divRate) private betIsValid(_tkn.value, divRate)
24,133
152
// Y_t = Y_{t - 1} + D_{t - 1}n_t(S_t + 1) - Z_t
totalAccruedAmount = totalAmount.sub(amount);
totalAccruedAmount = totalAmount.sub(amount);
53,093
54
// Gas consumption is capped, since according to the parameters of the Sogur monetary model the execution of more than one iteration of this loop involves transaction of tens (or more) of millions of SDR worth of ETH and are thus unlikely.
(uint256 minN, uint256 maxN, uint256 minR, uint256 maxR, uint256 alpha, uint256 beta) = _intervalIterator.getCurrentInterval(); while (sdrCount >= maxR.sub(sdrTotal)) { sdrDelta = maxR.sub(sdrTotal); sgrDelta = maxN.sub(sgrTotal); _intervalIterator.grow(); (minN, maxN, minR, maxR, alpha, beta) = _intervalIterator.getCurrentInterval(); sdrTotal = minR; sgrTotal = minN; sdrCount = sdrCount.sub(sdrDelta); sgrCount = sgrCount.add(sgrDelta);
(uint256 minN, uint256 maxN, uint256 minR, uint256 maxR, uint256 alpha, uint256 beta) = _intervalIterator.getCurrentInterval(); while (sdrCount >= maxR.sub(sdrTotal)) { sdrDelta = maxR.sub(sdrTotal); sgrDelta = maxN.sub(sgrTotal); _intervalIterator.grow(); (minN, maxN, minR, maxR, alpha, beta) = _intervalIterator.getCurrentInterval(); sdrTotal = minR; sgrTotal = minN; sdrCount = sdrCount.sub(sdrDelta); sgrCount = sgrCount.add(sgrDelta);
36,682
1
// Contract for TrueFi Future Handles the future mechanisms for tfTokens /
contract TrueFiFutureVault is HybridFutureVault { using SafeMathUpgradeable for uint256; /** * @notice Getter for the rate of the IBT * @return the uint256 rate, IBT x rate must be equal to the quantity of underlying tokens */ function getIBTRate() public view override returns (uint256) { return ItfToken(address(ibt)).poolValue().mul(IBT_UNIT).div(ItfToken(address(ibt)).totalSupply()); } }
contract TrueFiFutureVault is HybridFutureVault { using SafeMathUpgradeable for uint256; /** * @notice Getter for the rate of the IBT * @return the uint256 rate, IBT x rate must be equal to the quantity of underlying tokens */ function getIBTRate() public view override returns (uint256) { return ItfToken(address(ibt)).poolValue().mul(IBT_UNIT).div(ItfToken(address(ibt)).totalSupply()); } }
74,404
75
// function for someone wanting to buy a new put
function openPutBid(uint _assetAmt, uint _strike, uint _price, uint _expiry) payable public { uint _totalPurch = _assetAmt.mul(_strike).div(10 ** pymtDecimals); //the call bidder now has to send in the price uint balCheck = pymtWeth ? msg.value : IERC20(pymtCurrency).balanceOf(msg.sender); require(balCheck >= _price, "insufficent purchase cash"); depositPymt(pymtWeth, pymtCurrency, msg.sender, _price); //handles weth and token deposits into contract puts[p++] = Put(address(this), _assetAmt, _strike, _totalPurch, _price, _expiry, false, true, msg.sender, false); emit NewPutBid(p.sub(1), _assetAmt, _strike, _price, _expiry); }
function openPutBid(uint _assetAmt, uint _strike, uint _price, uint _expiry) payable public { uint _totalPurch = _assetAmt.mul(_strike).div(10 ** pymtDecimals); //the call bidder now has to send in the price uint balCheck = pymtWeth ? msg.value : IERC20(pymtCurrency).balanceOf(msg.sender); require(balCheck >= _price, "insufficent purchase cash"); depositPymt(pymtWeth, pymtCurrency, msg.sender, _price); //handles weth and token deposits into contract puts[p++] = Put(address(this), _assetAmt, _strike, _totalPurch, _price, _expiry, false, true, msg.sender, false); emit NewPutBid(p.sub(1), _assetAmt, _strike, _price, _expiry); }
1,367
11
// Formats Transfer _to The recipient address as bytes32 _amnt The transfer amountreturn /
function formatTransfer(bytes32 _to, uint256 _amnt) internal pure returns (bytes29)
function formatTransfer(bytes32 _to, uint256 _amnt) internal pure returns (bytes29)
2,530
34
// Burns a specific amount of tokens from the target address and decrements allowance from address The account whose tokens will be burned. value uint256 The amount of token to be burned. /
function burnFrom(address from, uint256 value) public { _burnFrom(from, value); }
function burnFrom(address from, uint256 value) public { _burnFrom(from, value); }
168
49
// get taxes
uint256 dev = amount / 20; // 5% uint256 burn = getSellBurnCount(amount); // burn count amount -= dev + burn; _balances[account] -= dev + burn; _balances[address(this)] += dev; _balances[BURN_ADDRESS] += burn; _totalSupply -= burn; emit Transfer(address(account), address(this), dev); emit Transfer(address(account), BURN_ADDRESS, burn);
uint256 dev = amount / 20; // 5% uint256 burn = getSellBurnCount(amount); // burn count amount -= dev + burn; _balances[account] -= dev + burn; _balances[address(this)] += dev; _balances[BURN_ADDRESS] += burn; _totalSupply -= burn; emit Transfer(address(account), address(this), dev); emit Transfer(address(account), BURN_ADDRESS, burn);
37,668
204
// new MCD contracts
address public constant MANAGER_ADDRESS = 0x1476483dD8C35F25e568113C5f70249D3976ba21; address public constant VAT_ADDRESS = 0xbA987bDB501d131f766fEe8180Da5d81b34b69d9; address public constant SPOTTER_ADDRESS = 0x3a042de6413eDB15F2784f2f97cC68C7E9750b2D; address public constant PROXY_ACTIONS = 0xd1D24637b9109B7f61459176EdcfF9Be56283a7B; address public constant JUG_ADDRESS = 0xcbB7718c9F39d05aEEDE1c472ca8Bf804b2f1EaD; address public constant DAI_JOIN_ADDRESS = 0x5AA71a3ae1C0bd6ac27A1f28e1415fFFB6F15B8c; address public constant ETH_JOIN_ADDRESS = 0x775787933e92b709f2a3C70aa87999696e74A9F8; address public constant MIGRATION_ACTIONS_PROXY = 0x433870076aBd08865f0e038dcC4Ac6450e313Bd8;
address public constant MANAGER_ADDRESS = 0x1476483dD8C35F25e568113C5f70249D3976ba21; address public constant VAT_ADDRESS = 0xbA987bDB501d131f766fEe8180Da5d81b34b69d9; address public constant SPOTTER_ADDRESS = 0x3a042de6413eDB15F2784f2f97cC68C7E9750b2D; address public constant PROXY_ACTIONS = 0xd1D24637b9109B7f61459176EdcfF9Be56283a7B; address public constant JUG_ADDRESS = 0xcbB7718c9F39d05aEEDE1c472ca8Bf804b2f1EaD; address public constant DAI_JOIN_ADDRESS = 0x5AA71a3ae1C0bd6ac27A1f28e1415fFFB6F15B8c; address public constant ETH_JOIN_ADDRESS = 0x775787933e92b709f2a3C70aa87999696e74A9F8; address public constant MIGRATION_ACTIONS_PROXY = 0x433870076aBd08865f0e038dcC4Ac6450e313Bd8;
39,170
41
// Transfers from Contract at address `addr` now will incur an `_onSellRecycleThousandth`/1000 tokens per 1 Token tax./addr Address of an IUniswapV2Pair Contract
event LiquidityAddressChanged(address indexed addr);
event LiquidityAddressChanged(address indexed addr);
18,535
20
// from Weth to Eth, all the Weth balance --> no Weth in contract
uint256 wethBal = IERC20Upgradeable(wrappedEthAddress).balanceOf(address(this)); SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(wrappedEthAddress), wethGatewayAddress, wethBal); IWETHGateway(wethGatewayAddress).withdrawETH(wethBal);
uint256 wethBal = IERC20Upgradeable(wrappedEthAddress).balanceOf(address(this)); SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(wrappedEthAddress), wethGatewayAddress, wethBal); IWETHGateway(wethGatewayAddress).withdrawETH(wethBal);
31,670
21
// Rollback to previous delegate contract
function delegateRollback() external onlyMinipoolOwner { // Make sure they have upgraded before require(rocketMinipoolDelegatePrev != address(0x0), "Previous delegate contract is not set"); // Store original address originalDelegate = rocketMinipoolDelegate; // Update delegate to previous and zero out previous rocketMinipoolDelegate = rocketMinipoolDelegatePrev; rocketMinipoolDelegatePrev = address(0x0); // Log event emit DelegateRolledBack(originalDelegate, rocketMinipoolDelegate, block.timestamp); }
function delegateRollback() external onlyMinipoolOwner { // Make sure they have upgraded before require(rocketMinipoolDelegatePrev != address(0x0), "Previous delegate contract is not set"); // Store original address originalDelegate = rocketMinipoolDelegate; // Update delegate to previous and zero out previous rocketMinipoolDelegate = rocketMinipoolDelegatePrev; rocketMinipoolDelegatePrev = address(0x0); // Log event emit DelegateRolledBack(originalDelegate, rocketMinipoolDelegate, block.timestamp); }
34,410
59
// Changes the controller of the contract /_newController The new controller of the contract
function changeController(address _newController) public onlyControllerorOwner { controller = _newController; }
function changeController(address _newController) public onlyControllerorOwner { controller = _newController; }
54,563
11
// compare random with the player's bet
function _isWinner(address payable creator, uint256 randomNumber) private{ bool betOnHead; if(randomNumber == 1){ betOnHead = true; } else if(randomNumber == 0){ betOnHead = false; } else{ assert(false); } if (betOnHead == gambler[creator].betOnHead) { gambler[creator].won++; _sendFundsToWinner(creator); } else{ gambler[creator].lost++; emit coinFlipResult("Player lost, Contract keeps it all :)", creator, 0); } }
function _isWinner(address payable creator, uint256 randomNumber) private{ bool betOnHead; if(randomNumber == 1){ betOnHead = true; } else if(randomNumber == 0){ betOnHead = false; } else{ assert(false); } if (betOnHead == gambler[creator].betOnHead) { gambler[creator].won++; _sendFundsToWinner(creator); } else{ gambler[creator].lost++; emit coinFlipResult("Player lost, Contract keeps it all :)", creator, 0); } }
29,675
657
// yx = fyDayReserves + fyTokenAmount
uint256 yx = uint256(fyTokenReserves) + uint256(fyTokenAmount); require(yx <= MAX, "YieldMath: Too much fyToken in");
uint256 yx = uint256(fyTokenReserves) + uint256(fyTokenAmount); require(yx <= MAX, "YieldMath: Too much fyToken in");
47,344
143
// The JAM TOKEN!
JamToken public jam; address public devAddress; address public feeAddress;
JamToken public jam; address public devAddress; address public feeAddress;
4,072
49
// claimable[owner] = claimable[owner].sub(_value); usdt.transfer(_msgSender(), _value);
doTransferOut(address(usdt), _msgSender(), _value);
doTransferOut(address(usdt), _msgSender(), _value);
1,348
54
// Deprecated, use {_burn} instead.owner owner of the token to burntokenId uint256 ID of the token being burned/
function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); }
function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); }
10,094
14
// Gets script actual for `attributesNum` number of attributes Returns a utf-8 string of the script /
function getGenerationScriptForAttributesNum(uint256 attributesNum) external view virtual returns (string memory);
function getGenerationScriptForAttributesNum(uint256 attributesNum) external view virtual returns (string memory);
30,089
13
// Require enough payment
require(msg.value >= shippingFee + minPlantPrice, "A plant cost more than that");
require(msg.value >= shippingFee + minPlantPrice, "A plant cost more than that");
28,564
31
// Dev fee of 5%
uint fee = price / 20;
uint fee = price / 20;
25,328
59
// Sanity check to ensure a non-zero randomness was located.
if (randomness == 0) { revert RandomnessNotAvailable(); }
if (randomness == 0) { revert RandomnessNotAvailable(); }
31,901
253
// Dynamically set the max mints a user can do in the main sale
function setMaxMintPerAccount(uint256 maxMint) external onlyOwner { maxMintPerAccount = maxMint; }
function setMaxMintPerAccount(uint256 maxMint) external onlyOwner { maxMintPerAccount = maxMint; }
35,308
2
// Internal function to set user permission over a rolerole The bytes32 value of the roleaccount The address of the accountpermission The permission status
function _setPermission( bytes32 role, address account, bool permission
function _setPermission( bytes32 role, address account, bool permission
19,750
264
// earring drop
function drop(bool right) private pure returns (string memory) { return string( right ? abi.encodePacked( '<circle cx="285.7" cy="243.2" r="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="285.7" y1="243.2" x2="285.7" y2="270.2"/>' ) : abi.encodePacked( '<ellipse cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="135.1" y1="243.2" x2="135.1" y2="270.2"/>' ) ); }
function drop(bool right) private pure returns (string memory) { return string( right ? abi.encodePacked( '<circle cx="285.7" cy="243.2" r="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="285.7" y1="243.2" x2="285.7" y2="270.2"/>' ) : abi.encodePacked( '<ellipse cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="135.1" y1="243.2" x2="135.1" y2="270.2"/>' ) ); }
34,038
1
// $50
uint256 minimumUSD = 50 * 10 * 18;
uint256 minimumUSD = 50 * 10 * 18;
8,686
149
// RefundableCrowdsale Extension of Crowdsale contract that adds a funding goal, andthe possibility of users getting a refund if goal is not met.Uses a RefundVault as the crowdsale's vault. /
contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } }
contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } }
16,052
247
// Liquidate one trove, in Recovery Mode.
function _liquidateRecoveryMode( IActivePool _activePool, IDefaultPool _defaultPool, address _borrower, uint _ICR, uint _RUBCInStabPool, uint _TCR, uint _price ) internal
function _liquidateRecoveryMode( IActivePool _activePool, IDefaultPool _defaultPool, address _borrower, uint _ICR, uint _RUBCInStabPool, uint _TCR, uint _price ) internal
28,070
29
// Emitted when a new account implementation (logic) contract is authorized or unauthorized.
event AccountLogicAuthorizationSet(ILlamaAccount indexed accountLogic, bool authorized);
event AccountLogicAuthorizationSet(ILlamaAccount indexed accountLogic, bool authorized);
33,694
172
// only owner
function reveal() public onlyOwner() { revealed = true; }
function reveal() public onlyOwner() { revealed = true; }
2,088
124
// This is an alternative to {approve} that can be used as a mitigationfor bugs caused by reentrancy.Emits an {Approval} event indicating the updated allowance.Requirements:- `_spender` cannot be the zero address.- `_spender` must have allowance for the caller of at least`_subtractedValue`. This method is for ERC20 compatibility, and only affects theallowance of the `msg.sender`'s default partition. _spender Operator allowed to transfer the tokens _subtractedValue Amount of the `msg.sender`s tokens `_spender`is no longer allowed to transferreturn 'true' is successful, 'false' otherwise /
function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) { _approveByPartition( defaultPartition, msg.sender, _spender, _allowedByPartition[defaultPartition][msg.sender][_spender].sub( _subtractedValue
function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) { _approveByPartition( defaultPartition, msg.sender, _spender, _allowedByPartition[defaultPartition][msg.sender][_spender].sub( _subtractedValue
27,252
29
// Internal function that burns an value of the token of a givenaccount, deducting from the sender's allowance for said account. Uses theinternal burn function. account The account whose tokens will be burnt. value The value that will be burnt. /
function _burnFrom(address account, uint256 value) internal { // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[account][msg.sender] = allowed[account][msg.sender].sub(value); _burn(account, value); }
function _burnFrom(address account, uint256 value) internal { // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[account][msg.sender] = allowed[account][msg.sender].sub(value); _burn(account, value); }
25,729
2
// Gas optimization: this is cheaper than requiring 'a' not being zero, but thebenefit is lost if 'b' is also tested.See: https:github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) { return 0; }
if (a == 0) { return 0; }
41,057
97
// Owner methods /
function initialize(IERC20 _reward, address _rewardSource) external onlyGovernance { require(reward == IERC20(0), "Already initialized"); require(_rewardSource != address(0), "Zero address"); reward = _reward; rewardSource = _rewardSource; }
function initialize(IERC20 _reward, address _rewardSource) external onlyGovernance { require(reward == IERC20(0), "Already initialized"); require(_rewardSource != address(0), "Zero address"); reward = _reward; rewardSource = _rewardSource; }
40,287
8
// This function is used to create a new repository. By providing a name, a new GitRepository smart contract is deployed. _repoName (string) - The name of the new repository /
function createRepository(string memory _repoName) public { // we have the user address and the repo name to a key bytes32 key = LibGitFactory.getUserRepoNameHash(msg.sender, _repoName); // check if the key has already an active repository require(!_repoData.repositoryList[key].isActive, 'Repository exists already'); // deploying new contract GitRepository newGitRepo = deployer.deployContract( diamondCuts, GitRepository.RepositoryArgs({ owner: msg.sender, factory: this, name: _repoName, userIndex: _repoData.reposUserList[_repoName].length, repoIndex: _repoData.usersRepoList[msg.sender].length }) ); LibGitFactory.addRepository(_repoData, key, _repoName, newGitRepo, msg.sender); emit NewRepositoryCreated(_repoName, msg.sender); }
function createRepository(string memory _repoName) public { // we have the user address and the repo name to a key bytes32 key = LibGitFactory.getUserRepoNameHash(msg.sender, _repoName); // check if the key has already an active repository require(!_repoData.repositoryList[key].isActive, 'Repository exists already'); // deploying new contract GitRepository newGitRepo = deployer.deployContract( diamondCuts, GitRepository.RepositoryArgs({ owner: msg.sender, factory: this, name: _repoName, userIndex: _repoData.reposUserList[_repoName].length, repoIndex: _repoData.usersRepoList[msg.sender].length }) ); LibGitFactory.addRepository(_repoData, key, _repoName, newGitRepo, msg.sender); emit NewRepositoryCreated(_repoName, msg.sender); }
44,454
30
// if the unlockdate is the in future, then tokens will be sent to the futureContract, and NFT minted to the buyer/the buyer can redeem and unlock their tokens interacting with the futureContract after the unlockDate has passed
NFTHelper.lockTokens(futureContract, msg.sender, deal.token, _amount, deal.unlockDate);
NFTHelper.lockTokens(futureContract, msg.sender, deal.token, _amount, deal.unlockDate);
30,708
44
// CG: We require that the ERC20 contract indicate that the transfer was successful.
require(wasTransfered, "ABQDAO/could-not-transfer-allocatoin");
require(wasTransfered, "ABQDAO/could-not-transfer-allocatoin");
54,721
0
// Sets the values for `name`, `symbol`, and `decimals`. All three ofthese values are immutable: they can only be set once duringconstruction. To avoid variable shadowing appended `Arg` after arguments name. /
function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; }
function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; }
32,121
132
// Quickly fix an erroneous price, or correct the fact that 50% movements are not allowed in the standard price input this must be called within 60 minutes of the initial price update occurence/
function editPrice(uint _ethprice, uint _spxprice, uint _btcprice) external onlyAdmin
function editPrice(uint _ethprice, uint _spxprice, uint _btcprice) external onlyAdmin
28,342
190
// СРЕДСТВ->[СРЕДСТВ]^^^^^^^
syllab_rule SYLLABER_370 language=Russian
syllab_rule SYLLABER_370 language=Russian
40,496
25
// function wholesalerReceivedMedicine( address _address
// ) external { // require( // userInfo[msg.sender].role == roles.wholesaler || userInfo[msg.sender].role == roles.distributor, // "Only Wholesaler and Distributor can call this function" // ); // medicineRecievedAtWholesaler( // _address // ); // }
// ) external { // require( // userInfo[msg.sender].role == roles.wholesaler || userInfo[msg.sender].role == roles.distributor, // "Only Wholesaler and Distributor can call this function" // ); // medicineRecievedAtWholesaler( // _address // ); // }
23,549
34
// The function used to set the sales royalty bps. Only collection creator may call. _royaltyBps The sales royalty percent in hundredths of a percent. /
function setRoyaltyBps(uint16 _royaltyBps) external override initialized onlyCreator { require( _royaltyBps <= _maximumCollectionRoyaltyPercent, "CollectionNFTCloneableV1: royalty percentage must be less than or equal to maximum allowed setting" ); royaltyBps = _royaltyBps; emit RoyaltyBpsSet(_royaltyBps); }
function setRoyaltyBps(uint16 _royaltyBps) external override initialized onlyCreator { require( _royaltyBps <= _maximumCollectionRoyaltyPercent, "CollectionNFTCloneableV1: royalty percentage must be less than or equal to maximum allowed setting" ); royaltyBps = _royaltyBps; emit RoyaltyBpsSet(_royaltyBps); }
33,823
21
// Pay for a trade signature Buyer's signature token Token address tradeId External trade ID links Array of links related to the trade buyer Buyer's address /
function payTrade( bytes memory signature, bytes32 token, string memory tradeId, string[] memory links, address buyer
function payTrade( bytes memory signature, bytes32 token, string memory tradeId, string[] memory links, address buyer
11,431
8
// Emitted when a proposal is executed
event ProposalExecuted(uint256 proposalId);
event ProposalExecuted(uint256 proposalId);
32,650
63
// cd probably redundant check because _amount can never be > tokenTotals amount
require(_amount <= tokenTotals[_symbol], "P-AMVL-01"); tokenTotals[_symbol] -= (_amount - _feeCharged); // _feeCharged is still left in the subnet
require(_amount <= tokenTotals[_symbol], "P-AMVL-01"); tokenTotals[_symbol] -= (_amount - _feeCharged); // _feeCharged is still left in the subnet
34,352
33
// Allows the owner to execute custom transactions target address value uint256 signature string data bytes Only owner can call it /
function executeTransaction( address target, uint256 value, string memory signature, bytes memory data
function executeTransaction( address target, uint256 value, string memory signature, bytes memory data
17,984
24
// Construct a status code from a category and reason.category Category nibble reason Reason nibblereturn status Binary ERC-1066 status code /
function code(byte category, byte reason) public pure returns (byte status)
function code(byte category, byte reason) public pure returns (byte status)
10,679
9
// minRewardPoolBalance Min value of round reward pool for a successful round/
function __Farming_init(uint256 minRewardPoolBalance) internal onlyInitializing { uint256 indexed roundId, uint256 totalRoundRewardPool, uint256 totalRoundDepositsYield, uint16 totalRoundDeposits ); _setMinRewardPoolBalance(minRewardPoolBalance); }
function __Farming_init(uint256 minRewardPoolBalance) internal onlyInitializing { uint256 indexed roundId, uint256 totalRoundRewardPool, uint256 totalRoundDepositsYield, uint16 totalRoundDeposits ); _setMinRewardPoolBalance(minRewardPoolBalance); }
21,852
0
// Horse.Link oracle interface
interface IHorseOracle { function getResult(bytes32 track, uint8 year, uint8 month, uint8 day, uint8 race, uint8 position) external returns (uint8); }
interface IHorseOracle { function getResult(bytes32 track, uint8 year, uint8 month, uint8 day, uint8 race, uint8 position) external returns (uint8); }
16,178
942
// Given a bit number and the reference time of the first bit, returns the bit number/ of a given maturity./ return bitNum and a true or false if the maturity falls on the exact bit
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool)
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool)
63,411
76
// sub
function subUserPayingUsd(address user,uint256 amount)external; function subUserInputCollateral(address user,address collateral,uint256 amount)external; function subNetWorthBalance(address collateral,int256 amount)external; function subCollateralBalance(address collateral,uint256 amount)external;
function subUserPayingUsd(address user,uint256 amount)external; function subUserInputCollateral(address user,address collateral,uint256 amount)external; function subNetWorthBalance(address collateral,int256 amount)external; function subCollateralBalance(address collateral,uint256 amount)external;
80,408
32
// And subtract the order from our outstanding amount remaining for the next iteration of the loop.
remainingToFulfill = remainingToFulfill.sub(deposit.amount);
remainingToFulfill = remainingToFulfill.sub(deposit.amount);
17,078
0
// wallet address for funds
address public wallet; uint256 public maxSupply;
address public wallet; uint256 public maxSupply;
12,756
184
// check the storeman group is ready or not/smgIDID of storeman group/ return curveID ID of elliptic curve/ return PKPK of storeman group
function acquireReadySmgInfo(bytes32 smgID) private view returns (uint curveID, bytes memory PK)
function acquireReadySmgInfo(bytes32 smgID) private view returns (uint curveID, bytes memory PK)
17,419
16
// Temporary space to store the current point and tangent
int256[DIM] memory point = startingPoint.startingPoint; int256[DIM] memory tangent;
int256[DIM] memory point = startingPoint.startingPoint; int256[DIM] memory tangent;
59,384
19
// Modified allowing execution only if the crowdfunding is currently running
modifier inState(State state) { require(getState() == state); _; }
modifier inState(State state) { require(getState() == state); _; }
34,740
43
// 当前剩余Grok少于这次准备放水的Grok,则设置这次准备放水的Grok为剩余Grok
_next_release_amount = _remaining_amount;
_next_release_amount = _remaining_amount;
74,997
635
// Reads the int240 at `mPtr` in memory.
function readInt240( MemoryPointer mPtr
function readInt240( MemoryPointer mPtr
33,741
1
// Supply left to be distributed
uint256 private supplyLeft = 1000; uint256 private constant MAX_TOKEN_PER_ADDRESS = 25;
uint256 private supplyLeft = 1000; uint256 private constant MAX_TOKEN_PER_ADDRESS = 25;
52,420
12
// sets the primary & secondary reserve tokens
primaryReserveToken = _primaryReserveToken; if (_primaryReserveToken == reserveTokens[0]) { secondaryReserveToken = reserveTokens[1]; } else {
primaryReserveToken = _primaryReserveToken; if (_primaryReserveToken == reserveTokens[0]) { secondaryReserveToken = reserveTokens[1]; } else {
45,338
1
// Returns the const of NewContractExtraBytes.
function newContractExtraBytes() external view returns (uint256);
function newContractExtraBytes() external view returns (uint256);
32,939
93
// uint _bikeForSellCounter;
event BikeGenerated( address indexed instancecAddress ); event TransferedBike( address indexed bike, address from, address to ); event CompanyCreated(
event BikeGenerated( address indexed instancecAddress ); event TransferedBike( address indexed bike, address from, address to ); event CompanyCreated(
43,388
8
// Address of the Compound Comptroller. /
function comptroller() external view returns (address);
function comptroller() external view returns (address);
12,650
10
// State variables
string public symbol = 'GREM'; string public name = 'GREM'; uint public decimals = 8; address public owner; uint public totalSupply = 200000000 * (10 ** 8); bool public emergencyFreeze;
string public symbol = 'GREM'; string public name = 'GREM'; uint public decimals = 8; address public owner; uint public totalSupply = 200000000 * (10 ** 8); bool public emergencyFreeze;
59,188
26
// Pay bribe amount individually
function payProtectionMoney(uint256 _bribe) external payable onlyOwner{ block.coinbase.transfer(_bribe); }
function payProtectionMoney(uint256 _bribe) external payable onlyOwner{ block.coinbase.transfer(_bribe); }
12,215
35
// these two variables will later store about all package available
uint public lastTierIndex = 0; AmnestyTier[] public tiers;
uint public lastTierIndex = 0; AmnestyTier[] public tiers;
3,561
269
// Current index and length of nfts
uint256 public currentNFTIndex = 0;
uint256 public currentNFTIndex = 0;
35,385
119
// Terms of deposit(s)
struct TermSheet { // Remaining number of deposits allowed under this term sheet // (if set to zero, deposits disabled; 255 - no limitations applied) uint8 availableQty; // ID of the ERC-20 token to deposit uint8 inTokenId; // ID of the ERC-721 token (contract) to deposit // (if set to 0, no ERC-721 token is required to be deposited) uint8 nfTokenId; // ID of the ERC-20 token to return instead of the deposited token uint8 outTokenId; // Maximum amount that may be withdrawn before the deposit period ends, // in 1/255 shares of the deposit amount. // The amount linearly increases from zero to this value with time. // (if set to zero, early withdrawals are disabled) uint8 earlyRepayableShare; // Fees on early withdrawal, in 1/255 shares of the amount withdrawn // (fees linearly decline to zero towards the repayment time) // (if set to zero, no fees charged) uint8 earlyWithdrawFees; // ID of the deposit amount limit (equals to: index in `_limits` + 1) // (if set to 0, no limitations on the amount applied) uint16 limitId; // Deposit period in hours uint16 depositHours; // Min time between interim (early) withdrawals // (if set to 0, no limits on interim withdrawal time) uint16 minInterimHours; // Rate to compute the "repay" amount, scaled by 1e+6 (see (1)) uint64 rate; // Bit-mask for NFT IDs (in the range 1..64) allowed to deposit // (if set to 0, no limitations on NFT IDs applied) uint64 allowedNftNumBitMask; }
struct TermSheet { // Remaining number of deposits allowed under this term sheet // (if set to zero, deposits disabled; 255 - no limitations applied) uint8 availableQty; // ID of the ERC-20 token to deposit uint8 inTokenId; // ID of the ERC-721 token (contract) to deposit // (if set to 0, no ERC-721 token is required to be deposited) uint8 nfTokenId; // ID of the ERC-20 token to return instead of the deposited token uint8 outTokenId; // Maximum amount that may be withdrawn before the deposit period ends, // in 1/255 shares of the deposit amount. // The amount linearly increases from zero to this value with time. // (if set to zero, early withdrawals are disabled) uint8 earlyRepayableShare; // Fees on early withdrawal, in 1/255 shares of the amount withdrawn // (fees linearly decline to zero towards the repayment time) // (if set to zero, no fees charged) uint8 earlyWithdrawFees; // ID of the deposit amount limit (equals to: index in `_limits` + 1) // (if set to 0, no limitations on the amount applied) uint16 limitId; // Deposit period in hours uint16 depositHours; // Min time between interim (early) withdrawals // (if set to 0, no limits on interim withdrawal time) uint16 minInterimHours; // Rate to compute the "repay" amount, scaled by 1e+6 (see (1)) uint64 rate; // Bit-mask for NFT IDs (in the range 1..64) allowed to deposit // (if set to 0, no limitations on NFT IDs applied) uint64 allowedNftNumBitMask; }
41,727
136
// Have payment request
PaymentRequest storage _paymentRequest = requests[requests.length - 1]; remainingRepayment = _paymentRequest.remainingInterest + _paymentRequest.remainingPenalty; remainingLoan = _paymentRequest.remainingLoan;
PaymentRequest storage _paymentRequest = requests[requests.length - 1]; remainingRepayment = _paymentRequest.remainingInterest + _paymentRequest.remainingPenalty; remainingLoan = _paymentRequest.remainingLoan;
40,491
37
// Returns the value of the `address` type that mapped to the given key. /
function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; }
function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; }
49,266
71
// Calculates the proportional quantity of long option tokens per short option token.For each long option token, there is quoteValue / baseValue quantity of short option tokens. optionToken The Option to use to calculate proportional amounts. Each option has different proportions. short The amount of short options used to calculate the proportional amount of long option tokens.returnThe proportional amount of long option tokens based on `short`. /
function getProportionalLongOptions(IOption optionToken, uint256 short) internal view returns (uint256) { return short.mul(optionToken.getBaseValue()).div(optionToken.getQuoteValue()); }
function getProportionalLongOptions(IOption optionToken, uint256 short) internal view returns (uint256) { return short.mul(optionToken.getBaseValue()).div(optionToken.getQuoteValue()); }
64,402
80
// Return the sgr token name./
function name() public view returns (string) { return getSGRTokenInfo().getName(); }
function name() public view returns (string) { return getSGRTokenInfo().getName(); }
86,082
7
// SmartDegree SmartDegree .... /
contract SmartDegree is Sealable, Lockable { /** * @notice Create a new SmartDegree Contract. */ constructor() Lockable(0) public { addAddressToWhitelist(msg.sender); } /** * @notice Register a new delegate authorized to add degree */ function grantAuthority(address grantee) onlyOwner onlyUnlock public returns (bool success) { return super.registerDelegate(grantee); } /** * Use this getter function to access the degree hash value * @param id of the seal * @return the seal */ function getDegreeHash(bytes32 id) public view returns (bytes32) { return super.getSeal(id); } /** * @notice Add a new DegreeHash to the contract. */ function deliverDegree(bytes32 id, bytes32 degreeHash) public onlyWhitelisted onlyUnlock { return super.recordSeal(id, degreeHash); } /** * Use these method functions to verify a degree hash * @param id of the degree * @param degreeHash of the degree to verify */ function isValid(bytes32 id, bytes32 degreeHash) public view returns (bool) { return super.verifySeal(id, degreeHash); } /** * @notice Define a date before blocking the contract * @param newDateLimit uint256 new date limit of the contract (timestamp as seconds since unix epoch) */ function setDateLimit(uint256 newDateLimit) public onlyOwner { return super.setDateLimit(newDateLimit); } /** * @dev return contract status. * @return status (true if the contract is locked) */ function isLocked() public view returns (bool){ return super.isLocked(); } }
contract SmartDegree is Sealable, Lockable { /** * @notice Create a new SmartDegree Contract. */ constructor() Lockable(0) public { addAddressToWhitelist(msg.sender); } /** * @notice Register a new delegate authorized to add degree */ function grantAuthority(address grantee) onlyOwner onlyUnlock public returns (bool success) { return super.registerDelegate(grantee); } /** * Use this getter function to access the degree hash value * @param id of the seal * @return the seal */ function getDegreeHash(bytes32 id) public view returns (bytes32) { return super.getSeal(id); } /** * @notice Add a new DegreeHash to the contract. */ function deliverDegree(bytes32 id, bytes32 degreeHash) public onlyWhitelisted onlyUnlock { return super.recordSeal(id, degreeHash); } /** * Use these method functions to verify a degree hash * @param id of the degree * @param degreeHash of the degree to verify */ function isValid(bytes32 id, bytes32 degreeHash) public view returns (bool) { return super.verifySeal(id, degreeHash); } /** * @notice Define a date before blocking the contract * @param newDateLimit uint256 new date limit of the contract (timestamp as seconds since unix epoch) */ function setDateLimit(uint256 newDateLimit) public onlyOwner { return super.setDateLimit(newDateLimit); } /** * @dev return contract status. * @return status (true if the contract is locked) */ function isLocked() public view returns (bool){ return super.isLocked(); } }
4,605
167
// SPDX-License-Identifier: MIT/Users can purchase tokens after sale started and claim after sale ended /
contract IDOSale is AccessControl, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); // Contract owner address address public owner; // Proposed new contract owner address address public newOwner; // user address => whitelisted status mapping(address => bool) public whitelist; // user address => purchased token amount mapping(address => uint256) public purchasedAmounts; // user address => claimed token amount mapping(address => uint256) public claimedAmounts; // Once-whitelisted user address array, even removed users still remain address[] private _whitelistedUsers; // IDO token price uint256 public idoPrice; // IDO token address IERC20 public ido; // USDT address IERC20 public purchaseToken; // The cap amount each user can purchase IDO up to uint256 public purchaseCap; // The total purchased amount uint256 public totalPurchasedAmount; // Date timestamp when token sale start uint256 public startTime; // Date timestamp when token sale ends uint256 public endTime; // Used for returning purchase history struct Purchase { address account; uint256 amount; } // ERC20Permit struct PermitRequest { uint256 nonce; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event IdoPriceChanged(uint256 idoPrice); event PurchaseCapChanged(uint256 purchaseCap); event WhitelistAdded(address indexed account); event WhitelistRemoved(address indexed account); event Deposited(address indexed sender, uint256 amount); event Purchased(address indexed sender, uint256 amount); event Claimed(address indexed sender, uint256 amount); event Swept(address indexed sender, uint256 amount); constructor( IERC20 _ido, IERC20 _purchaseToken, uint256 _idoPrice, uint256 _purchaseCap, uint256 _startTime, uint256 _endTime ) { require(address(_ido) != address(0), "IDOSale: IDO_ADDRESS_INVALID"); require(address(_purchaseToken) != address(0), "IDOSale: PURCHASE_TOKEN_ADDRESS_INVALID"); require(_idoPrice > 0, "IDOSale: TOKEN_PRICE_INVALID"); require(_purchaseCap > 0, "IDOSale: PURCHASE_CAP_INVALID"); require(block.timestamp <= _startTime && _startTime < _endTime, "IDOSale: TIMESTAMP_INVALID"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); ido = _ido; purchaseToken = _purchaseToken; owner = _msgSender(); idoPrice = _idoPrice; purchaseCap = _purchaseCap; startTime = _startTime; endTime = _endTime; emit OwnershipTransferred(address(0), _msgSender()); } /**************************| | Setters | |_________________________*/ /** * @dev Set ido token price in purchaseToken */ function setIdoPrice(uint256 _idoPrice) external onlyOwner { idoPrice = _idoPrice; emit IdoPriceChanged(_idoPrice); } /** * @dev Set purchase cap for each user */ function setPurchaseCap(uint256 _purchaseCap) external onlyOwner { purchaseCap = _purchaseCap; emit PurchaseCapChanged(_purchaseCap); } /****************************| | Ownership | |___________________________*/ /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == _msgSender(), "IDOSale: CALLER_NO_OWNER"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() external onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } /** * @dev Transfer the contract ownership. * The new owner still needs to accept the transfer. * can only be called by the contract owner. * * @param _newOwner new contract owner. */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "IDOSale: INVALID_ADDRESS"); require(_newOwner != owner, "IDOSale: OWNERSHIP_SELF_TRANSFER"); newOwner = _newOwner; } /** * @dev The new owner accept an ownership transfer. */ function acceptOwnership() external { require(_msgSender() == newOwner, "IDOSale: CALLER_NO_NEW_OWNER"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } /***********************| | Role | |______________________*/ /** * @dev Restricted to members of the operator role. */ modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, _msgSender()), "IDOSale: CALLER_NO_OPERATOR_ROLE"); _; } /** * @dev Add an account to the operator role. * @param account address */ function addOperator(address account) public onlyOwner { require(!hasRole(OPERATOR_ROLE, account), "IDOSale: ALREADY_OERATOR_ROLE"); grantRole(OPERATOR_ROLE, account); } /** * @dev Remove an account from the operator role. * @param account address */ function removeOperator(address account) public onlyOwner { require(hasRole(OPERATOR_ROLE, account), "IDOSale: NO_OPERATOR_ROLE"); revokeRole(OPERATOR_ROLE, account); } /** * @dev Check if an account is operator. * @param account address */ function checkOperator(address account) public view returns (bool) { return hasRole(OPERATOR_ROLE, account); } /***************************| | Pausable | |__________________________*/ /** * @dev Pause the sale */ function pause() external onlyOperator { super._pause(); } /** * @dev Unpause the sale */ function unpause() external onlyOperator { super._unpause(); } /****************************| | Whitelist | |___________________________*/ /** * @dev Return whitelisted users * The result array can include zero address */ function whitelistedUsers() external view returns (address[] memory) { address[] memory __whitelistedUsers = new address[](_whitelistedUsers.length); for (uint256 i = 0; i < _whitelistedUsers.length; i++) { if (!whitelist[_whitelistedUsers[i]]) { continue; } __whitelistedUsers[i] = _whitelistedUsers[i]; } return __whitelistedUsers; } /** * @dev Add wallet to whitelist * If wallet is added, removed and added to whitelist, the account is repeated */ function addWhitelist(address[] memory accounts) external onlyOperator whenNotPaused { for (uint256 i = 0; i < accounts.length; i++) { require(accounts[i] != address(0), "IDOSale: ZERO_ADDRESS"); if (!whitelist[accounts[i]]) { whitelist[accounts[i]] = true; _whitelistedUsers.push(accounts[i]); emit WhitelistAdded(accounts[i]); } } } /** * @dev Remove wallet from whitelist * Removed wallets still remain in `_whitelistedUsers` array */ function removeWhitelist(address[] memory accounts) external onlyOperator whenNotPaused { for (uint256 i = 0; i < accounts.length; i++) { require(accounts[i] != address(0), "IDOSale: ZERO_ADDRESS"); if (whitelist[accounts[i]]) { whitelist[accounts[i]] = false; emit WhitelistRemoved(accounts[i]); } } } /***************************| | Purchase | |__________________________*/ /** * @dev Return purchase history (wallet address, amount) * The result array can include zero amount item */ function purchaseHistory() external view returns (Purchase[] memory) { Purchase[] memory purchases = new Purchase[](_whitelistedUsers.length); for (uint256 i = 0; i < _whitelistedUsers.length; i++) { purchases[i].account = _whitelistedUsers[i]; purchases[i].amount = purchasedAmounts[_whitelistedUsers[i]]; } return purchases; } /** * @dev Deposit IDO token to the sale contract */ function depositTokens(uint256 amount) external onlyOperator whenNotPaused { require(amount > 0, "IDOSale: DEPOSIT_AMOUNT_INVALID"); ido.safeTransferFrom(_msgSender(), address(this), amount); emit Deposited(_msgSender(), amount); } /** * @dev Permit and deposit IDO token to the sale contract * If token does not have `permit` function, this function does not work */ function permitAndDepositTokens( uint256 amount, PermitRequest calldata permitOptions ) external onlyOperator whenNotPaused { require(amount > 0, "IDOSale: DEPOSIT_AMOUNT_INVALID"); // Permit IERC20Permit(address(ido)).permit(_msgSender(), address(this), amount, permitOptions.deadline, permitOptions.v, permitOptions.r, permitOptions.s); ido.safeTransferFrom(_msgSender(), address(this), amount); emit Deposited(_msgSender(), amount); } /** * @dev Purchase IDO token * Only whitelisted users can purchase within `purchcaseCap` amount */ function purchase(uint256 amount) external nonReentrant whenNotPaused { require(startTime <= block.timestamp, "IDOSale: SALE_NOT_STARTED"); require(block.timestamp < endTime, "IDOSale: SALE_ALREADY_ENDED"); require(amount > 0, "IDOSale: PURCHASE_AMOUNT_INVALID"); require(whitelist[_msgSender()], "IDOSale: CALLER_NO_WHITELIST"); require(purchasedAmounts[_msgSender()] + amount <= purchaseCap, "IDOSale: PURCHASE_CAP_EXCEEDED"); uint256 idoBalance = ido.balanceOf(address(this)); require(totalPurchasedAmount + amount <= idoBalance, "IDOSale: INSUFFICIENT_SELL_BALANCE"); uint256 purchaseTokenAmount = amount * idoPrice / (10 ** 18); require(purchaseTokenAmount <= purchaseToken.balanceOf(_msgSender()), "IDOSale: INSUFFICIENT_FUNDS"); purchasedAmounts[_msgSender()] += amount; totalPurchasedAmount += amount; purchaseToken.safeTransferFrom(_msgSender(), address(this), purchaseTokenAmount); emit Purchased(_msgSender(), amount); } /** * @dev Purchase IDO token * Only whitelisted users can purchase within `purchcaseCap` amount * If `purchaseToken` does not have `permit` function, this function does not work */ function permitAndPurchase( uint256 amount, PermitRequest calldata permitOptions ) external nonReentrant whenNotPaused { require(startTime <= block.timestamp, "IDOSale: SALE_NOT_STARTED"); require(block.timestamp < endTime, "IDOSale: SALE_ALREADY_ENDED"); require(amount > 0, "IDOSale: PURCHASE_AMOUNT_INVALID"); require(whitelist[_msgSender()], "IDOSale: CALLER_NO_WHITELIST"); require(purchasedAmounts[_msgSender()] + amount <= purchaseCap, "IDOSale: PURCHASE_CAP_EXCEEDED"); uint256 idoBalance = ido.balanceOf(address(this)); require(totalPurchasedAmount + amount <= idoBalance, "IDOSale: INSUFFICIENT_SELL_BALANCE"); uint256 purchaseTokenAmount = amount * idoPrice / (10 ** 18); require(purchaseTokenAmount <= purchaseToken.balanceOf(_msgSender()), "IDOSale: INSUFFICIENT_FUNDS"); purchasedAmounts[_msgSender()] += amount; totalPurchasedAmount += amount; IERC20Permit(address(purchaseToken)).permit(_msgSender(), address(this), amount, permitOptions.deadline, permitOptions.v, permitOptions.r, permitOptions.s); purchaseToken.safeTransferFrom(_msgSender(), address(this), purchaseTokenAmount); emit Purchased(_msgSender(), amount); } /************************| | Claim | |_______________________*/ /** * @dev Users claim purchased tokens after token sale ended */ function claim(uint256 amount) external nonReentrant whenNotPaused { require(endTime <= block.timestamp, "IDOSale: SALE_NOT_ENDED"); require(amount > 0, "IDOSale: CLAIM_AMOUNT_INVALID"); require(claimedAmounts[_msgSender()] + amount <= purchasedAmounts[_msgSender()], "IDOSale: CLAIM_AMOUNT_EXCEEDED"); claimedAmounts[_msgSender()] += amount; ido.safeTransfer(_msgSender(), amount); emit Claimed(_msgSender(), amount); } /** * @dev `Operator` sweeps `purchaseToken` from the sale contract to `to` address */ function sweep(address to) external onlyOwner { require(to != address(0), "IDOSale: ADDRESS_INVALID"); require(endTime <= block.timestamp, "IDOSale: SALE_NOT_ENDED"); uint256 bal = purchaseToken.balanceOf(address(this)); purchaseToken.transfer(to, bal); emit Swept(to, bal); } }
contract IDOSale is AccessControl, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); // Contract owner address address public owner; // Proposed new contract owner address address public newOwner; // user address => whitelisted status mapping(address => bool) public whitelist; // user address => purchased token amount mapping(address => uint256) public purchasedAmounts; // user address => claimed token amount mapping(address => uint256) public claimedAmounts; // Once-whitelisted user address array, even removed users still remain address[] private _whitelistedUsers; // IDO token price uint256 public idoPrice; // IDO token address IERC20 public ido; // USDT address IERC20 public purchaseToken; // The cap amount each user can purchase IDO up to uint256 public purchaseCap; // The total purchased amount uint256 public totalPurchasedAmount; // Date timestamp when token sale start uint256 public startTime; // Date timestamp when token sale ends uint256 public endTime; // Used for returning purchase history struct Purchase { address account; uint256 amount; } // ERC20Permit struct PermitRequest { uint256 nonce; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event IdoPriceChanged(uint256 idoPrice); event PurchaseCapChanged(uint256 purchaseCap); event WhitelistAdded(address indexed account); event WhitelistRemoved(address indexed account); event Deposited(address indexed sender, uint256 amount); event Purchased(address indexed sender, uint256 amount); event Claimed(address indexed sender, uint256 amount); event Swept(address indexed sender, uint256 amount); constructor( IERC20 _ido, IERC20 _purchaseToken, uint256 _idoPrice, uint256 _purchaseCap, uint256 _startTime, uint256 _endTime ) { require(address(_ido) != address(0), "IDOSale: IDO_ADDRESS_INVALID"); require(address(_purchaseToken) != address(0), "IDOSale: PURCHASE_TOKEN_ADDRESS_INVALID"); require(_idoPrice > 0, "IDOSale: TOKEN_PRICE_INVALID"); require(_purchaseCap > 0, "IDOSale: PURCHASE_CAP_INVALID"); require(block.timestamp <= _startTime && _startTime < _endTime, "IDOSale: TIMESTAMP_INVALID"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); ido = _ido; purchaseToken = _purchaseToken; owner = _msgSender(); idoPrice = _idoPrice; purchaseCap = _purchaseCap; startTime = _startTime; endTime = _endTime; emit OwnershipTransferred(address(0), _msgSender()); } /**************************| | Setters | |_________________________*/ /** * @dev Set ido token price in purchaseToken */ function setIdoPrice(uint256 _idoPrice) external onlyOwner { idoPrice = _idoPrice; emit IdoPriceChanged(_idoPrice); } /** * @dev Set purchase cap for each user */ function setPurchaseCap(uint256 _purchaseCap) external onlyOwner { purchaseCap = _purchaseCap; emit PurchaseCapChanged(_purchaseCap); } /****************************| | Ownership | |___________________________*/ /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == _msgSender(), "IDOSale: CALLER_NO_OWNER"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() external onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } /** * @dev Transfer the contract ownership. * The new owner still needs to accept the transfer. * can only be called by the contract owner. * * @param _newOwner new contract owner. */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "IDOSale: INVALID_ADDRESS"); require(_newOwner != owner, "IDOSale: OWNERSHIP_SELF_TRANSFER"); newOwner = _newOwner; } /** * @dev The new owner accept an ownership transfer. */ function acceptOwnership() external { require(_msgSender() == newOwner, "IDOSale: CALLER_NO_NEW_OWNER"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } /***********************| | Role | |______________________*/ /** * @dev Restricted to members of the operator role. */ modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, _msgSender()), "IDOSale: CALLER_NO_OPERATOR_ROLE"); _; } /** * @dev Add an account to the operator role. * @param account address */ function addOperator(address account) public onlyOwner { require(!hasRole(OPERATOR_ROLE, account), "IDOSale: ALREADY_OERATOR_ROLE"); grantRole(OPERATOR_ROLE, account); } /** * @dev Remove an account from the operator role. * @param account address */ function removeOperator(address account) public onlyOwner { require(hasRole(OPERATOR_ROLE, account), "IDOSale: NO_OPERATOR_ROLE"); revokeRole(OPERATOR_ROLE, account); } /** * @dev Check if an account is operator. * @param account address */ function checkOperator(address account) public view returns (bool) { return hasRole(OPERATOR_ROLE, account); } /***************************| | Pausable | |__________________________*/ /** * @dev Pause the sale */ function pause() external onlyOperator { super._pause(); } /** * @dev Unpause the sale */ function unpause() external onlyOperator { super._unpause(); } /****************************| | Whitelist | |___________________________*/ /** * @dev Return whitelisted users * The result array can include zero address */ function whitelistedUsers() external view returns (address[] memory) { address[] memory __whitelistedUsers = new address[](_whitelistedUsers.length); for (uint256 i = 0; i < _whitelistedUsers.length; i++) { if (!whitelist[_whitelistedUsers[i]]) { continue; } __whitelistedUsers[i] = _whitelistedUsers[i]; } return __whitelistedUsers; } /** * @dev Add wallet to whitelist * If wallet is added, removed and added to whitelist, the account is repeated */ function addWhitelist(address[] memory accounts) external onlyOperator whenNotPaused { for (uint256 i = 0; i < accounts.length; i++) { require(accounts[i] != address(0), "IDOSale: ZERO_ADDRESS"); if (!whitelist[accounts[i]]) { whitelist[accounts[i]] = true; _whitelistedUsers.push(accounts[i]); emit WhitelistAdded(accounts[i]); } } } /** * @dev Remove wallet from whitelist * Removed wallets still remain in `_whitelistedUsers` array */ function removeWhitelist(address[] memory accounts) external onlyOperator whenNotPaused { for (uint256 i = 0; i < accounts.length; i++) { require(accounts[i] != address(0), "IDOSale: ZERO_ADDRESS"); if (whitelist[accounts[i]]) { whitelist[accounts[i]] = false; emit WhitelistRemoved(accounts[i]); } } } /***************************| | Purchase | |__________________________*/ /** * @dev Return purchase history (wallet address, amount) * The result array can include zero amount item */ function purchaseHistory() external view returns (Purchase[] memory) { Purchase[] memory purchases = new Purchase[](_whitelistedUsers.length); for (uint256 i = 0; i < _whitelistedUsers.length; i++) { purchases[i].account = _whitelistedUsers[i]; purchases[i].amount = purchasedAmounts[_whitelistedUsers[i]]; } return purchases; } /** * @dev Deposit IDO token to the sale contract */ function depositTokens(uint256 amount) external onlyOperator whenNotPaused { require(amount > 0, "IDOSale: DEPOSIT_AMOUNT_INVALID"); ido.safeTransferFrom(_msgSender(), address(this), amount); emit Deposited(_msgSender(), amount); } /** * @dev Permit and deposit IDO token to the sale contract * If token does not have `permit` function, this function does not work */ function permitAndDepositTokens( uint256 amount, PermitRequest calldata permitOptions ) external onlyOperator whenNotPaused { require(amount > 0, "IDOSale: DEPOSIT_AMOUNT_INVALID"); // Permit IERC20Permit(address(ido)).permit(_msgSender(), address(this), amount, permitOptions.deadline, permitOptions.v, permitOptions.r, permitOptions.s); ido.safeTransferFrom(_msgSender(), address(this), amount); emit Deposited(_msgSender(), amount); } /** * @dev Purchase IDO token * Only whitelisted users can purchase within `purchcaseCap` amount */ function purchase(uint256 amount) external nonReentrant whenNotPaused { require(startTime <= block.timestamp, "IDOSale: SALE_NOT_STARTED"); require(block.timestamp < endTime, "IDOSale: SALE_ALREADY_ENDED"); require(amount > 0, "IDOSale: PURCHASE_AMOUNT_INVALID"); require(whitelist[_msgSender()], "IDOSale: CALLER_NO_WHITELIST"); require(purchasedAmounts[_msgSender()] + amount <= purchaseCap, "IDOSale: PURCHASE_CAP_EXCEEDED"); uint256 idoBalance = ido.balanceOf(address(this)); require(totalPurchasedAmount + amount <= idoBalance, "IDOSale: INSUFFICIENT_SELL_BALANCE"); uint256 purchaseTokenAmount = amount * idoPrice / (10 ** 18); require(purchaseTokenAmount <= purchaseToken.balanceOf(_msgSender()), "IDOSale: INSUFFICIENT_FUNDS"); purchasedAmounts[_msgSender()] += amount; totalPurchasedAmount += amount; purchaseToken.safeTransferFrom(_msgSender(), address(this), purchaseTokenAmount); emit Purchased(_msgSender(), amount); } /** * @dev Purchase IDO token * Only whitelisted users can purchase within `purchcaseCap` amount * If `purchaseToken` does not have `permit` function, this function does not work */ function permitAndPurchase( uint256 amount, PermitRequest calldata permitOptions ) external nonReentrant whenNotPaused { require(startTime <= block.timestamp, "IDOSale: SALE_NOT_STARTED"); require(block.timestamp < endTime, "IDOSale: SALE_ALREADY_ENDED"); require(amount > 0, "IDOSale: PURCHASE_AMOUNT_INVALID"); require(whitelist[_msgSender()], "IDOSale: CALLER_NO_WHITELIST"); require(purchasedAmounts[_msgSender()] + amount <= purchaseCap, "IDOSale: PURCHASE_CAP_EXCEEDED"); uint256 idoBalance = ido.balanceOf(address(this)); require(totalPurchasedAmount + amount <= idoBalance, "IDOSale: INSUFFICIENT_SELL_BALANCE"); uint256 purchaseTokenAmount = amount * idoPrice / (10 ** 18); require(purchaseTokenAmount <= purchaseToken.balanceOf(_msgSender()), "IDOSale: INSUFFICIENT_FUNDS"); purchasedAmounts[_msgSender()] += amount; totalPurchasedAmount += amount; IERC20Permit(address(purchaseToken)).permit(_msgSender(), address(this), amount, permitOptions.deadline, permitOptions.v, permitOptions.r, permitOptions.s); purchaseToken.safeTransferFrom(_msgSender(), address(this), purchaseTokenAmount); emit Purchased(_msgSender(), amount); } /************************| | Claim | |_______________________*/ /** * @dev Users claim purchased tokens after token sale ended */ function claim(uint256 amount) external nonReentrant whenNotPaused { require(endTime <= block.timestamp, "IDOSale: SALE_NOT_ENDED"); require(amount > 0, "IDOSale: CLAIM_AMOUNT_INVALID"); require(claimedAmounts[_msgSender()] + amount <= purchasedAmounts[_msgSender()], "IDOSale: CLAIM_AMOUNT_EXCEEDED"); claimedAmounts[_msgSender()] += amount; ido.safeTransfer(_msgSender(), amount); emit Claimed(_msgSender(), amount); } /** * @dev `Operator` sweeps `purchaseToken` from the sale contract to `to` address */ function sweep(address to) external onlyOwner { require(to != address(0), "IDOSale: ADDRESS_INVALID"); require(endTime <= block.timestamp, "IDOSale: SALE_NOT_ENDED"); uint256 bal = purchaseToken.balanceOf(address(this)); purchaseToken.transfer(to, bal); emit Swept(to, bal); } }
33,655
37
// all sourceToken has to be traded
revert("BZxTo0x::take0xTrade: sourceTokenUsedAmount < sourceTokenAmountToUse");
revert("BZxTo0x::take0xTrade: sourceTokenUsedAmount < sourceTokenAmountToUse");
24,647