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
5
// Change the base URI for returning metadata _baseTokenURI the respective base URI/
function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; }
function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; }
63,160
274
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
bytes32 public priceIdentifier;
8,060
151
// Save/update amount value staked by the delegator
_snapshotDelegatorStake(_poolStakingAddress, _staker);
_snapshotDelegatorStake(_poolStakingAddress, _staker);
7,259
419
// round 27
ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q);
ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q);
48,706
88
// change the minimum burn rate to acquire a slot
function setMinBurnRate(uint poolId, uint newMinBurnRate) external poolOwnerOnly(poolId) { Pool storage pool = pools[poolId]; pool.minimumBurnRateWeiPerBlock = newMinBurnRate; }
function setMinBurnRate(uint poolId, uint newMinBurnRate) external poolOwnerOnly(poolId) { Pool storage pool = pools[poolId]; pool.minimumBurnRateWeiPerBlock = newMinBurnRate; }
62,881
766
// Reads the bytes7 at `mPtr` in memory.
function readBytes7(MemoryPointer mPtr) internal pure returns (bytes7 value) { assembly { value := mload(mPtr) } }
function readBytes7(MemoryPointer mPtr) internal pure returns (bytes7 value) { assembly { value := mload(mPtr) } }
40,440
29
// _uriSuffix new suffix value to be used in tokenURI /
function setUriSuffix(string calldata _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; }
function setUriSuffix(string calldata _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; }
32,448
148
// but not on the total amount of tokens
return(totalTokens);
return(totalTokens);
74,830
10
// This function sets the maximum allowable deposit for the given ERC20 token/asset_source Contract address for given ERC20 token/maximum_amount Maximum deposit amount/nonce Vega-assigned single-use number that provides replay attack protection/signatures Vega-supplied signature bundle of a validator-signed order/See MultisigControl for more about signatures/Emits Asset_Deposit_Maximum_Set if successful
function set_deposit_maximum(address asset_source, uint256 maximum_amount, uint256 nonce, bytes memory signatures) public override { require(listed_tokens[asset_source], "asset not listed"); bytes memory message = abi.encode(asset_source, maximum_amount, nonce, 'set_deposit_maximum'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); maximum_deposits[asset_source] = maximum_amount; emit Asset_Deposit_Maximum_Set(asset_source, maximum_amount, nonce); }
function set_deposit_maximum(address asset_source, uint256 maximum_amount, uint256 nonce, bytes memory signatures) public override { require(listed_tokens[asset_source], "asset not listed"); bytes memory message = abi.encode(asset_source, maximum_amount, nonce, 'set_deposit_maximum'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); maximum_deposits[asset_source] = maximum_amount; emit Asset_Deposit_Maximum_Set(asset_source, maximum_amount, nonce); }
31,461
105
// Transfer lighthouse fee to lighthouse worker directly
require(xrt.transferFrom(liability.promisor(), tx.origin, liability.lighthouseFee()));
require(xrt.transferFrom(liability.promisor(), tx.origin, liability.lighthouseFee()));
5,474
21
// Function to check balance of contract
function getContractBalance() public view returns (uint256)
function getContractBalance() public view returns (uint256)
24,254
134
// Landlord
else if(ownerType == 2){ getLandNFT().ownerOf(landId); }
else if(ownerType == 2){ getLandNFT().ownerOf(landId); }
43,827
54
// Reward token
PlotXToken private rewardToken;
PlotXToken private rewardToken;
3,989
17
// balanceOf : Displya token balance of given address /
function balanceOf(address tokenOwner) virtual override public view returns (uint balance) { return balances[tokenOwner]; }
function balanceOf(address tokenOwner) virtual override public view returns (uint balance) { return balances[tokenOwner]; }
11,755
11
// Gets the balance of the specified address. _owner The address to query the the balance of.return An uint256 representing the amount owned by the passed address. /
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
38,241
92
// amount in real tokens/wei if ether
function withdrawDepositsByProfile(uint32 profile_id) external { for(uint32 i=0; i < customers_deposits[msg.sender].length; i++){ if (depositIsExtractable(customers_deposits[msg.sender][i]) && profile_id == customers_deposits[msg.sender][i].deposit_profile_id){ withdrawDepositById(i); } } emit CustomerWithdrawDepositsByProfileId(msg.sender, profile_id); }
function withdrawDepositsByProfile(uint32 profile_id) external { for(uint32 i=0; i < customers_deposits[msg.sender].length; i++){ if (depositIsExtractable(customers_deposits[msg.sender][i]) && profile_id == customers_deposits[msg.sender][i].deposit_profile_id){ withdrawDepositById(i); } } emit CustomerWithdrawDepositsByProfileId(msg.sender, profile_id); }
33,025
90
// Validate that address and bytes array lengths match. Validate address array is not emptyand contains no duplicate elements.A Array of addresses B Array of bytes /
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); }
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); }
23,375
151
// The buy slope of the bonding curve./ Does not affect the financial model, only the granularity of COT./This is the numerator component of the fractional value.
uint public buySlopeNum;
uint public buySlopeNum;
77,933
409
// An event for tracking the creation of a new Staker.
event FarmCreated(address indexed farmAddress, address indexed creator);
event FarmCreated(address indexed farmAddress, address indexed creator);
41,451
7
// Remove Leading Zeroes
while (fractionalPartTemp != 0 && fractionalPartTemp % 10 == 0) { fractionalPartTemp /= 10; if (powerRemaining > 0) { powerRemaining--; }
while (fractionalPartTemp != 0 && fractionalPartTemp % 10 == 0) { fractionalPartTemp /= 10; if (powerRemaining > 0) { powerRemaining--; }
43,652
26
// add pending rewards to remainder to be claimed by user later, if there is any existing stake
uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; stakers[msg.sender].stakedTokens = tokens.add(stakers[msg.sender].stakedTokens); stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend= totalDividends; stakers[msg.sender].round = round; (bool _isStakeholder) = isStakeholder(msg.sender); if(!_isStakeholder) farmTime[msg.sender] = block.timestamp;
uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; stakers[msg.sender].stakedTokens = tokens.add(stakers[msg.sender].stakedTokens); stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend= totalDividends; stakers[msg.sender].round = round; (bool _isStakeholder) = isStakeholder(msg.sender); if(!_isStakeholder) farmTime[msg.sender] = block.timestamp;
58,675
24
// Update reinvest minimum threshold before a deposit newValue min threshold in wei /
function updateMinTokensToReinvestBeforeDeposit(uint newValue) external onlyOwner { emit UpdateMinTokensToReinvestBeforeDeposit(MIN_TOKENS_TO_REINVEST_BEFORE_DEPOSIT, newValue); MIN_TOKENS_TO_REINVEST_BEFORE_DEPOSIT = newValue; }
function updateMinTokensToReinvestBeforeDeposit(uint newValue) external onlyOwner { emit UpdateMinTokensToReinvestBeforeDeposit(MIN_TOKENS_TO_REINVEST_BEFORE_DEPOSIT, newValue); MIN_TOKENS_TO_REINVEST_BEFORE_DEPOSIT = newValue; }
40,586
9
// enum which contains type of contract /
ContractType private _contractType;
ContractType private _contractType;
24,504
43
// Reset the counter
tokenReserved = 0;
tokenReserved = 0;
40,574
15
// ROUND DATA
mapping (uint256 => FFEIFDatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
mapping (uint256 => FFEIFDatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
32,206
89
// Get the true value of dai claimable by an account, factoring in the interest splitOverrides usual ERC20 balanceOf() to show true claimable balance across wallets and dAppsaccount Account to check
function balanceOf(address account) public view returns (uint256) { return _dai(account, _simulateChi()); }
function balanceOf(address account) public view returns (uint256) { return _dai(account, _simulateChi()); }
35,591
56
// use user limit
userPendingWithdrawals[msg.sender] = userPendingWithdrawals[msg.sender]+msg.value-prices[0]; pendingWithdrawalEvent(msg.sender,userPendingWithdrawals[msg.sender]+msg.value-prices[0]); cities[cityId].purchases = cities[cityId].purchases+1; userPendingWithdrawals[cities[cityId].mayor] += prices[3]; pendingWithdrawalEvent(cities[cityId].mayor,prices[3]); if (countries[citiesCountries[cityId]].president==0) { userPendingWithdrawals[creator] += prices[2];
userPendingWithdrawals[msg.sender] = userPendingWithdrawals[msg.sender]+msg.value-prices[0]; pendingWithdrawalEvent(msg.sender,userPendingWithdrawals[msg.sender]+msg.value-prices[0]); cities[cityId].purchases = cities[cityId].purchases+1; userPendingWithdrawals[cities[cityId].mayor] += prices[3]; pendingWithdrawalEvent(cities[cityId].mayor,prices[3]); if (countries[citiesCountries[cityId]].president==0) { userPendingWithdrawals[creator] += prices[2];
80,375
55
// adding defence for the city
function addDefence() payable withFee public { // getting coordinates of the current player uint32 coord = _requirePlayer(msg.sender); // ensure these are coordinates of a real city _requireCity(coord); // the defence cannot exceed 8 uint8 defence = cities[coord].defence; require(defence < 8); // city players must qualify for upgrade: there should be min amount of people on that cell // before level upgrade // - - - - - - commented out for beta-testing - - - - - - // uint num = cells[coord].num; if (defence == 2) { require(num >= 10); } else if (defence == 3) { require(num >= 50); } else if (defence == 4) { require(num >= 100); } else if (defence == 5) { require(num >= 250); } else if (defence == 6) { require(num >= 1000); } else if (defence == 7) { require(num >= 2500); } // increase defence cities[coord].defence = defence + 1; CityUpdate(coord, cities[coord].title, cities[coord].defence); }
function addDefence() payable withFee public { // getting coordinates of the current player uint32 coord = _requirePlayer(msg.sender); // ensure these are coordinates of a real city _requireCity(coord); // the defence cannot exceed 8 uint8 defence = cities[coord].defence; require(defence < 8); // city players must qualify for upgrade: there should be min amount of people on that cell // before level upgrade // - - - - - - commented out for beta-testing - - - - - - // uint num = cells[coord].num; if (defence == 2) { require(num >= 10); } else if (defence == 3) { require(num >= 50); } else if (defence == 4) { require(num >= 100); } else if (defence == 5) { require(num >= 250); } else if (defence == 6) { require(num >= 1000); } else if (defence == 7) { require(num >= 2500); } // increase defence cities[coord].defence = defence + 1; CityUpdate(coord, cities[coord].title, cities[coord].defence); }
13,336
91
// Tell us invest was success
Invested(receiver, weiAmount, tokenAmount);
Invested(receiver, weiAmount, tokenAmount);
10,590
19
// NOTE: storage layout must be the same as contract A
uint public num; address public sender; uint public value;
uint public num; address public sender; uint public value;
6,462
60
// Increments the total number of uncommitted storage slots. /
function incrementTotalUncommittedContractStorage() override public authenticated
function incrementTotalUncommittedContractStorage() override public authenticated
56,468
74
// The left child is taking the place of node, so we update it&39;s parent to be the original parent of the node.
Node storage newRoot = index.nodes[originalRoot.left]; newRoot.parent = originalRoot.parent;
Node storage newRoot = index.nodes[originalRoot.left]; newRoot.parent = originalRoot.parent;
35,031
33
// list NFTs
function listNft( address _contractAddress, uint256 _nftId, uint256 _price
function listNft( address _contractAddress, uint256 _nftId, uint256 _price
11,146
12
// total transferred amount
uint public totalOutboundAmount = 0;
uint public totalOutboundAmount = 0;
4,973
69
// fromToken Address of the source token toToken Address of the destination token fromAmount Amount of source tokens to be swapped toAmount Minimum destination token amount expected out of this swap expectedAmount Expected amount of destination tokens without slippage beneficiary Beneficiary address0 then 100% will be transferred to beneficiary. Pass 10000 for 100% referrer referral id path Route to be taken for this swap to take place /
struct SellData { IERC20 fromToken; IERC20 toToken; uint256 fromAmount; uint256 toAmount; uint256 expectedAmount; address payable beneficiary; string referrer; Utils.Path[] path; }
struct SellData { IERC20 fromToken; IERC20 toToken; uint256 fromAmount; uint256 toAmount; uint256 expectedAmount; address payable beneficiary; string referrer; Utils.Path[] path; }
37,879
152
// Sets new block on which presales first stage will end/This method should only be used in ongoing presale if something goes wrong/firstStageBlockEnd_ The block number on which presales first stage will end/ return default return True after everything is processed
function setFirstStageBlockEnd(uint firstStageBlockEnd_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _firstStageBlockEnd; require(oldValue != firstStageBlockEnd_, "Value is already set!"); _firstStageBlockEnd = firstStageBlockEnd_; emit FirstStageBlockEndChanged(oldValue, firstStageBlockEnd_); return true; }
function setFirstStageBlockEnd(uint firstStageBlockEnd_) public onlyRole(MODERATOR_ROLE) override returns (bool) { uint oldValue = _firstStageBlockEnd; require(oldValue != firstStageBlockEnd_, "Value is already set!"); _firstStageBlockEnd = firstStageBlockEnd_; emit FirstStageBlockEndChanged(oldValue, firstStageBlockEnd_); return true; }
13,902
260
// calculate amount of ETH we need
(uint256 requiredETH, uint256 amountWant)= getFlashLoanParams(want, amountDesired);
(uint256 requiredETH, uint256 amountWant)= getFlashLoanParams(want, amountDesired);
40,438
464
// Reads the bytes4 at `mPtr` in memory.
function readBytes4( MemoryPointer mPtr
function readBytes4( MemoryPointer mPtr
19,810
67
// Otherwise, revert with a generic error.
_revertInvalidCallToConduit(conduit);
_revertInvalidCallToConduit(conduit);
17,064
99
// Restore tax and liquidity fees
_taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ restoreAllFee(); }
_taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ restoreAllFee(); }
35,235
14
// bytesStorage /
function setStorage(BytesData storage self, bytes memory key, bytes memory innerKey, bytes memory value) internal { self._storage[key][innerKey] = value; }
function setStorage(BytesData storage self, bytes memory key, bytes memory innerKey, bytes memory value) internal { self._storage[key][innerKey] = value; }
42,553
20
// Safe token transfer function, just in case if rounding errorcauses pool to not have enough reward tokens _token The address of then token to transfer _to The address that will receive `_amount` `rewardToken` _amount The amount to send to `_to` /
function safeTokenTransfer( ERC20 _token, address _to, uint256 _amount
function safeTokenTransfer( ERC20 _token, address _to, uint256 _amount
20,928
4
// Emitted when attempting to buy hTokens with a zero amount of underlying.
error HifiPool__BuyHTokenUnderlyingZero();
error HifiPool__BuyHTokenUnderlyingZero();
38,132
3
// cant already be floating
require( !ships[_contract][_shipId].floating );
require( !ships[_contract][_shipId].floating );
13,505
0
// Events /
event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required);
event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required);
45,949
35
// Msg Value/ Owner Address should not be equal to zero
require(initiatedProduct[_productId]._ownerAddress != address(0x0),"Product does not exists");
require(initiatedProduct[_productId]._ownerAddress != address(0x0),"Product does not exists");
44,146
8
// return When the actual report was made if one was made /
function getReportTimestamp() public view returns (uint256) { return reportTimestamp; }
function getReportTimestamp() public view returns (uint256) { return reportTimestamp; }
24,394
3
// Liquidates a leveraged asset; meant to be called from an LToken contract asset Asset to swap from userShare User's ratio of received tokens liquidatorShare Liquidator's ratio of received tokens poolShare Pool's ration of received tokens numberOfAssetTokens Number of asset tokens to swap user Address of the user liquidator Address of the liquidatorreturn uint Amount of cUSD user received /
function liquidateLeveragedAsset(address asset, uint userShare, uint liquidatorShare, uint poolShare, uint numberOfAssetTokens, address user, address liquidator) external returns (uint);
function liquidateLeveragedAsset(address asset, uint userShare, uint liquidatorShare, uint poolShare, uint numberOfAssetTokens, address user, address liquidator) external returns (uint);
7,936
0
// @TODO: Fill in the constructor parameters!
address payable wallet, PupperCoin token, uint cap, uint rate, uint goal, uint open, uint close ) Crowdsale(rate, wallet, token)
address payable wallet, PupperCoin token, uint cap, uint rate, uint goal, uint open, uint close ) Crowdsale(rate, wallet, token)
10,595
4
// send all Ether to owner Owner can receive Ether since the address of owner is payable
(bool success, ) = owner.call{value: amount}("");
(bool success, ) = owner.call{value: amount}("");
26,220
58
// gives square. batchplies x by x/
function sq(uint256 x) internal pure returns (uint256)
function sq(uint256 x) internal pure returns (uint256)
37,902
1
// silence state mutability warning without generating bytecode - see https:github.com/ethereum/solidity/issues/2691
return msg.data;
return msg.data;
7,296
43
// An event emitted when a new proposal is created
event ProposalCreated(uint indexed id, address indexed proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
event ProposalCreated(uint indexed id, address indexed proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
83,133
48
// Deleverage
uint256 flashLoanAmount = AaveLibPub.quoteReserveFromBase((1 ether * debt - ltv * collateral) / (1 ether - ltv), usdc, 6, priceOracle); ILendingPool(lendingPool).flashLoanSimple( address(this), usdc, flashLoanAmount, abi.encode(flashLoanAmount + (flashLoanAmount * (ILendingPool(lendingPool).FLASHLOAN_PREMIUM_TOTAL()) / 10000)), 0 );
uint256 flashLoanAmount = AaveLibPub.quoteReserveFromBase((1 ether * debt - ltv * collateral) / (1 ether - ltv), usdc, 6, priceOracle); ILendingPool(lendingPool).flashLoanSimple( address(this), usdc, flashLoanAmount, abi.encode(flashLoanAmount + (flashLoanAmount * (ILendingPool(lendingPool).FLASHLOAN_PREMIUM_TOTAL()) / 10000)), 0 );
11,495
47
// A user has passed KYC verification, store them on the blockchain in the order it happened.This will be cleared once the ICO completes, see closeIco(). ---- ICO-Platform Note ----The horizon-globex.com ICO platform's registered KYC provider submits their approvalfor this Contributor to particpate using the ICO-Platform portal.Each Contributor will then be sent the Ethereum, Bitcoin and IBAN account numbers todeposit their Approved Contribution in exchange for VOX Tokens.-- End ICO-Platform Note --who The user's address. /
function kycApproved(address who) public onlyKycProvider { require(!isIcoComplete, "The ICO phase has ended, you can no longer approve."); require(who != 0x0, "Cannot approve a null address."); kycValidated.push(who); }
function kycApproved(address who) public onlyKycProvider { require(!isIcoComplete, "The ICO phase has ended, you can no longer approve."); require(who != 0x0, "Cannot approve a null address."); kycValidated.push(who); }
11,543
32
// Return the log in base 2, following the selected rounding direction, of a positive value.Returns 0 if given 0. /
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } }
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } }
20,638
136
// ========== HOOKS ========== // Override _beforeStake() hook to collect the deposit fee and update associated state /
function _beforeStake( address _account, uint256 _amount
function _beforeStake( address _account, uint256 _amount
32,321
16
// Current winning bid
uint256 public lastBid; uint256 public lastBidTime; address payable public winning; event Bid(address who, uint256 amount); event Won(address who, uint256 amount);
uint256 public lastBid; uint256 public lastBidTime; address payable public winning; event Bid(address who, uint256 amount); event Won(address who, uint256 amount);
20,115
169
// Check whether the endEarningsPool is initialised If it is not initialised set it's cumulative factors so that they can be used when a delegator next claims earnings as the start cumulative factors (see delegatorCumulativeStakeAndFees())
Transcoder storage t = transcoders[del.delegateAddress]; EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound]; if (endEarningsPool.cumulativeRewardFactor == 0) { uint256 lastRewardRound = t.lastRewardRound; if (lastRewardRound < _endRound) { endEarningsPool.cumulativeRewardFactor = cumulativeFactorsPool(t, lastRewardRound) .cumulativeRewardFactor; }
Transcoder storage t = transcoders[del.delegateAddress]; EarningsPool.Data storage endEarningsPool = t.earningsPoolPerRound[_endRound]; if (endEarningsPool.cumulativeRewardFactor == 0) { uint256 lastRewardRound = t.lastRewardRound; if (lastRewardRound < _endRound) { endEarningsPool.cumulativeRewardFactor = cumulativeFactorsPool(t, lastRewardRound) .cumulativeRewardFactor; }
33,956
0
// Maps users to tokens to spender addresses and information about the approval on the token/Indexed in the order of token owner address, token address, spender address/The stored word saves the allowed amount, expiration on the allowance, and nonce
mapping(address => mapping(address => mapping(address => PackedAllowance))) public allowance;
mapping(address => mapping(address => mapping(address => PackedAllowance))) public allowance;
2,424
109
// AaveDistributionManager Accounting contract to manage multiple staking distributions Aave /
contract AaveDistributionManager is IAaveDistributionManager { using SafeMath for uint256; struct AssetData { uint128 emissionPerSecond; uint128 lastUpdateTimestamp; uint256 index; mapping(address => uint256) users; } uint256 public immutable DISTRIBUTION_END; address public immutable EMISSION_MANAGER; uint8 public constant PRECISION = 18; mapping(address => AssetData) public assets; event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); constructor(address emissionManager, uint256 distributionDuration) public { DISTRIBUTION_END = block.timestamp.add(distributionDuration); EMISSION_MANAGER = emissionManager; } /** * @dev Configures the distribution of rewards for a list of assets * @param assetsConfigInput The list of configurations to apply **/ function configureAssets(DistributionTypes.AssetConfigInput[] calldata assetsConfigInput) external override { require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER'); for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param underlyingAsset The address used as key in the distribution, for example sAAVE or the aTokens addresses on Aave * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex(oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked); if (newIndex != oldIndex) { assetConfig.index = newIndex; emit AssetIndexUpdated(underlyingAsset, newIndex); } assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal pure returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)).div(10**uint256(PRECISION)); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= DISTRIBUTION_END ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) public view returns (uint256) { return assets[asset].users[user]; } }
contract AaveDistributionManager is IAaveDistributionManager { using SafeMath for uint256; struct AssetData { uint128 emissionPerSecond; uint128 lastUpdateTimestamp; uint256 index; mapping(address => uint256) users; } uint256 public immutable DISTRIBUTION_END; address public immutable EMISSION_MANAGER; uint8 public constant PRECISION = 18; mapping(address => AssetData) public assets; event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); constructor(address emissionManager, uint256 distributionDuration) public { DISTRIBUTION_END = block.timestamp.add(distributionDuration); EMISSION_MANAGER = emissionManager; } /** * @dev Configures the distribution of rewards for a list of assets * @param assetsConfigInput The list of configurations to apply **/ function configureAssets(DistributionTypes.AssetConfigInput[] calldata assetsConfigInput) external override { require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER'); for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param underlyingAsset The address used as key in the distribution, for example sAAVE or the aTokens addresses on Aave * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex(oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked); if (newIndex != oldIndex) { assetConfig.index = newIndex; emit AssetIndexUpdated(underlyingAsset, newIndex); } assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal pure returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)).div(10**uint256(PRECISION)); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= DISTRIBUTION_END ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) public view returns (uint256) { return assets[asset].users[user]; } }
41,140
136
// Initialises a newly created instance/_totalSupply Total amount of Color Coin tokens available./_founder Address of the founder wallet/_admin Address of the admin wallet/_pixelCoinSupply Amount of tokens dedicated for Pixel program/_pixelAccount Address of the account that keeps coins for the Pixel program
constructor(uint256 _totalSupply, address payable _founder, address _admin, uint256 _pixelCoinSupply, address _pixelAccount ) public ColorCoinWithPixel (_totalSupply, _founder, _admin, _pixelCoinSupply, _pixelAccount)
constructor(uint256 _totalSupply, address payable _founder, address _admin, uint256 _pixelCoinSupply, address _pixelAccount ) public ColorCoinWithPixel (_totalSupply, _founder, _admin, _pixelCoinSupply, _pixelAccount)
37,959
233
// Upgrade token functions
function freezeToken() onlyOwner public { token.pause(); }
function freezeToken() onlyOwner public { token.pause(); }
86,320
11
// Check if poolToken was initialized
modifier poolTokenSet() { require(address(poolToken) != address(0x0), "poolToken not set"); _; }
modifier poolTokenSet() { require(address(poolToken) != address(0x0), "poolToken not set"); _; }
23,039
196
// Update the free memory pointer to allocate.
mstore(0x40, m)
mstore(0x40, m)
1,197
167
// Authorize / Deauthorize / Authorize users for an address be permitted to make record modifications /
function addUser(
function addUser(
62,733
27
// this is deployed on mainnet at:0x38aEfE9e8E0Fc938475bfC6d7E52aE28D39FEBD8
contract Fomo3d { // create some data tracking vars for testing bool public depositSuccessful_; uint256 public successfulTransactions_; uint256 public gasBefore_; uint256 public gasAfter_; // create forwarder instance Forwarder Jekyll_Island_Inc; // take addr for forwarder in constructor arguments constructor(address _addr) public { // set up forwarder to point to its contract location Jekyll_Island_Inc = Forwarder(_addr); } // some fomo3d function that deposits to Forwarder function someFunction() public payable { // grab gas left gasBefore_ = gasleft(); // deposit to forwarder, uses low level call so forwards all gas if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit()")))) { // give fomo3d work to do that needs gas. what better way than storage // write calls, since their so costly. depositSuccessful_ = false; gasAfter_ = gasleft(); } else { depositSuccessful_ = true; successfulTransactions_++; gasAfter_ = gasleft(); } } // some fomo3d function that deposits to Forwarder function someFunction2() public payable { // grab gas left gasBefore_ = gasleft(); // deposit to forwarder, uses low level call so forwards all gas if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit2()")))) { // give fomo3d work to do that needs gas. what better way than storage // write calls, since their so costly. depositSuccessful_ = false; gasAfter_ = gasleft(); } else { depositSuccessful_ = true; successfulTransactions_++; gasAfter_ = gasleft(); } } // some fomo3d function that deposits to Forwarder function someFunction3() public payable { // grab gas left gasBefore_ = gasleft(); // deposit to forwarder, uses low level call so forwards all gas if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit3()")))) { // give fomo3d work to do that needs gas. what better way than storage // write calls, since their so costly. depositSuccessful_ = false; gasAfter_ = gasleft(); } else { depositSuccessful_ = true; successfulTransactions_++; gasAfter_ = gasleft(); } } // some fomo3d function that deposits to Forwarder function someFunction4() public payable { // grab gas left gasBefore_ = gasleft(); // deposit to forwarder, uses low level call so forwards all gas if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit4()")))) { // give fomo3d work to do that needs gas. what better way than storage // write calls, since their so costly. depositSuccessful_ = false; gasAfter_ = gasleft(); } else { depositSuccessful_ = true; successfulTransactions_++; gasAfter_ = gasleft(); } } // for data tracking lets make a function to check this contracts balance function checkBalance() public view returns(uint256) { return(address(this).balance); } }
contract Fomo3d { // create some data tracking vars for testing bool public depositSuccessful_; uint256 public successfulTransactions_; uint256 public gasBefore_; uint256 public gasAfter_; // create forwarder instance Forwarder Jekyll_Island_Inc; // take addr for forwarder in constructor arguments constructor(address _addr) public { // set up forwarder to point to its contract location Jekyll_Island_Inc = Forwarder(_addr); } // some fomo3d function that deposits to Forwarder function someFunction() public payable { // grab gas left gasBefore_ = gasleft(); // deposit to forwarder, uses low level call so forwards all gas if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit()")))) { // give fomo3d work to do that needs gas. what better way than storage // write calls, since their so costly. depositSuccessful_ = false; gasAfter_ = gasleft(); } else { depositSuccessful_ = true; successfulTransactions_++; gasAfter_ = gasleft(); } } // some fomo3d function that deposits to Forwarder function someFunction2() public payable { // grab gas left gasBefore_ = gasleft(); // deposit to forwarder, uses low level call so forwards all gas if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit2()")))) { // give fomo3d work to do that needs gas. what better way than storage // write calls, since their so costly. depositSuccessful_ = false; gasAfter_ = gasleft(); } else { depositSuccessful_ = true; successfulTransactions_++; gasAfter_ = gasleft(); } } // some fomo3d function that deposits to Forwarder function someFunction3() public payable { // grab gas left gasBefore_ = gasleft(); // deposit to forwarder, uses low level call so forwards all gas if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit3()")))) { // give fomo3d work to do that needs gas. what better way than storage // write calls, since their so costly. depositSuccessful_ = false; gasAfter_ = gasleft(); } else { depositSuccessful_ = true; successfulTransactions_++; gasAfter_ = gasleft(); } } // some fomo3d function that deposits to Forwarder function someFunction4() public payable { // grab gas left gasBefore_ = gasleft(); // deposit to forwarder, uses low level call so forwards all gas if (!address(Jekyll_Island_Inc).call.value(msg.value)(bytes4(keccak256("deposit4()")))) { // give fomo3d work to do that needs gas. what better way than storage // write calls, since their so costly. depositSuccessful_ = false; gasAfter_ = gasleft(); } else { depositSuccessful_ = true; successfulTransactions_++; gasAfter_ = gasleft(); } } // for data tracking lets make a function to check this contracts balance function checkBalance() public view returns(uint256) { return(address(this).balance); } }
51,845
124
// Constructor Caveat emptor: this base contract is intended for inheritance by the Little Phil crowdsale only/
constructor() public { // setup the map of bonus-rates for each SaleState tier createSalesTierConfigMap(); }
constructor() public { // setup the map of bonus-rates for each SaleState tier createSalesTierConfigMap(); }
76,136
0
// collateral Asset used as a loan collateral. For a definition see { MultiToken dependency lib }. /
struct LOAN { uint8 status; address borrower; uint40 expiration; address loanAssetAddress; uint256 loanRepayAmount; MultiToken.Asset collateral; }
struct LOAN { uint8 status; address borrower; uint40 expiration; address loanAssetAddress; uint256 loanRepayAmount; MultiToken.Asset collateral; }
10,884
21
// PokumiWar Sebastien Gazeau Manage Pokmi's Pokumi War game /
contract PokumiWar is ERC1155, AccessControl, ERC1155Receiver, ERC1155Burnable, ERC1155Pausable { using Counters for Counters.Counter; struct InitialDataGame { string idPokumi; uint warrior; } struct InitialSeason { address player; string idPokumi; } struct Season { address winner; uint8 nbrOfDay; uint nbrOfWarrior; } Counters.Counter private seasonIds; uint private randNonce; bool public warIsStarted; address[] public players; mapping(string => uint) private pokumiArmy; mapping(uint => Season) public seasons; constructor() ERC1155("PokumiWarrrior"){ _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); } event ReceivedERC1155(address operator, address from, uint256 id, uint256 values, bytes data); event ReceivedBatchERC1155(address operator, address from, uint256[] ids, uint256[] values, bytes data); event WinnerSeason(uint _seasonId,address _winner); event WarStarting(Season _season, uint _startDayWar); event DayConflit(uint _seasonId, uint _nbrOfDefeatedWarrior, uint _warDay); event WarriorEngaged(address _player, uint _season, uint _nbrOfWarriorEngader, uint _engagementDate); event SeasonStarted(uint _seasonStartDate); function initializeData(InitialDataGame[] memory pokumi) external onlyRole(DEFAULT_ADMIN_ROLE){ require(pokumi.length > 0, "intialize data empty"); for(uint i = 0; i <= pokumi.length -1; i++){ pokumiArmy[pokumi[i].idPokumi] = pokumi[i].warrior; } } /** * @dev start a new war season * @param season a table of players eligible for this season with the number of warriors assigned to them */ function startingSeason(InitialSeason[] memory season) external onlyRole(DEFAULT_ADMIN_ROLE) { require(season.length > 0, "intialize data empty"); warIsStarted = false; seasonIds.increment(); for(uint i = 0; i <= season.length -1; i++){ _mint(season[i].player, 1, pokumiArmy[season[i].idPokumi], ""); } emit SeasonStarted(block.timestamp); } /** * @dev allows a player to hire a certain number of warriors for the current season */ function engageInSeason(uint warrior) external { require(!warIsStarted, "the fights have already started"); require(warrior > 0, "send more warrior"); require(balanceOf(msg.sender, 1) >= warrior, "not enough warrior"); safeTransferFrom(msg.sender, address(this), 1, warrior, ""); for(uint i = 0; i < warrior; i++){ players.push(msg.sender); } emit WarriorEngaged(msg.sender, seasonIds.current(), warrior, block.timestamp); } /** * @dev starts the combat phase of the war * @return season_ current season information */ function startingWar() external onlyRole(DEFAULT_ADMIN_ROLE) returns(Season memory season_) { warIsStarted = true; seasons[seasonIds.current()].nbrOfDay = durationWar(players.length); seasons[seasonIds.current()].nbrOfWarrior = players.length; season_ = seasons[seasonIds.current()]; emit WarStarting(seasons[seasonIds.current()], block.timestamp); } /** * @dev manages every day of the war * @return players_ the warriors still present in the war */ function newDayConflict() external onlyRole(DEFAULT_ADMIN_ROLE) returns (address[] memory players_) { require(players.length > 3, "not enough warrior"); uint futurLength = (players.length / 2) + ((players.length % 2 == 0) ? 0 : 1); while(players.length > futurLength){ players[randMod(players.length-1)] = players[players.length - 1]; players.pop(); } emit DayConflit(seasonIds.current(), futurLength, block.timestamp); players_ = players; } /** * @dev Selecting the winner of the war */ function lastDayFight() external onlyRole(DEFAULT_ADMIN_ROLE) { require(players.length == 3 || players.length == 2, "there are too many warriors left"); seasons[seasonIds.current()].winner = players[randMod(players.length-1)]; delete players; emit WinnerSeason(seasonIds.current(),seasons[seasonIds.current()].winner); } /** * @dev Get the number of warrior for a Pokumi * @return players_ list of all participants */ function getAllParticipants() view external returns (address[] memory players_){ return players; } /** * @dev Get the number of warrior for a Pokumi * @param _id The id of the Pokumi * @return oneArmy_ number of warrior the requested Pokumi */ function getArmy(string memory _id) view external returns (uint oneArmy_){ oneArmy_ = pokumiArmy[_id]; } /** * @dev Getter for the number of warriors in the current season * @return nbrWarrior_ the number of warrior */ function getNbrWarrior() external view returns(uint nbrWarrior_){ nbrWarrior_ = players.length; } /** * @dev Getter for the current season * @return currentSeason_ the number of the season */ function getCurrentSeason() external view returns (uint currentSeason_) { return seasonIds.current(); } /** * @dev calculate the number of days that a war will last * @param x the number of warriors participating in the war * @return r the number of days of the war */ function durationWar(uint x) internal pure returns (uint8 r) { require (x > 0); if (x >= 2**128) { x >>= 128; r += 128; } if (x >= 2**64) { x >>= 64; r += 64; } if (x >= 2**32) { x >>= 32; r += 32; } if (x >= 2**16) { x >>= 16; r += 16; } if (x >= 2**8) { x >>= 8; r += 8; } if (x >= 2**4) { x >>= 4; r += 4; } if (x >= 2**2) { x >>= 2; r += 2; } if (x >= 2**1) { x >>= 1; r += 1; } } /** * @dev Generates a random number * @param _modulus number to get max range * @return random_ a random number * */ function randMod(uint _modulus) internal returns(uint random_) { randNonce++; random_ = uint(keccak256(abi.encodePacked(block.timestamp,msg.sender,randNonce))) % _modulus; } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Pausable) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external virtual override returns (bytes4){ emit ReceivedERC1155(operator, from, id, value, data); return IERC1155Receiver.onERC1155Received.selector; } function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external virtual override returns (bytes4){ emit ReceivedBatchERC1155(operator, from, ids, values, data); return IERC1155Receiver.onERC1155Received.selector; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC1155,ERC1155Receiver, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } }
contract PokumiWar is ERC1155, AccessControl, ERC1155Receiver, ERC1155Burnable, ERC1155Pausable { using Counters for Counters.Counter; struct InitialDataGame { string idPokumi; uint warrior; } struct InitialSeason { address player; string idPokumi; } struct Season { address winner; uint8 nbrOfDay; uint nbrOfWarrior; } Counters.Counter private seasonIds; uint private randNonce; bool public warIsStarted; address[] public players; mapping(string => uint) private pokumiArmy; mapping(uint => Season) public seasons; constructor() ERC1155("PokumiWarrrior"){ _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); } event ReceivedERC1155(address operator, address from, uint256 id, uint256 values, bytes data); event ReceivedBatchERC1155(address operator, address from, uint256[] ids, uint256[] values, bytes data); event WinnerSeason(uint _seasonId,address _winner); event WarStarting(Season _season, uint _startDayWar); event DayConflit(uint _seasonId, uint _nbrOfDefeatedWarrior, uint _warDay); event WarriorEngaged(address _player, uint _season, uint _nbrOfWarriorEngader, uint _engagementDate); event SeasonStarted(uint _seasonStartDate); function initializeData(InitialDataGame[] memory pokumi) external onlyRole(DEFAULT_ADMIN_ROLE){ require(pokumi.length > 0, "intialize data empty"); for(uint i = 0; i <= pokumi.length -1; i++){ pokumiArmy[pokumi[i].idPokumi] = pokumi[i].warrior; } } /** * @dev start a new war season * @param season a table of players eligible for this season with the number of warriors assigned to them */ function startingSeason(InitialSeason[] memory season) external onlyRole(DEFAULT_ADMIN_ROLE) { require(season.length > 0, "intialize data empty"); warIsStarted = false; seasonIds.increment(); for(uint i = 0; i <= season.length -1; i++){ _mint(season[i].player, 1, pokumiArmy[season[i].idPokumi], ""); } emit SeasonStarted(block.timestamp); } /** * @dev allows a player to hire a certain number of warriors for the current season */ function engageInSeason(uint warrior) external { require(!warIsStarted, "the fights have already started"); require(warrior > 0, "send more warrior"); require(balanceOf(msg.sender, 1) >= warrior, "not enough warrior"); safeTransferFrom(msg.sender, address(this), 1, warrior, ""); for(uint i = 0; i < warrior; i++){ players.push(msg.sender); } emit WarriorEngaged(msg.sender, seasonIds.current(), warrior, block.timestamp); } /** * @dev starts the combat phase of the war * @return season_ current season information */ function startingWar() external onlyRole(DEFAULT_ADMIN_ROLE) returns(Season memory season_) { warIsStarted = true; seasons[seasonIds.current()].nbrOfDay = durationWar(players.length); seasons[seasonIds.current()].nbrOfWarrior = players.length; season_ = seasons[seasonIds.current()]; emit WarStarting(seasons[seasonIds.current()], block.timestamp); } /** * @dev manages every day of the war * @return players_ the warriors still present in the war */ function newDayConflict() external onlyRole(DEFAULT_ADMIN_ROLE) returns (address[] memory players_) { require(players.length > 3, "not enough warrior"); uint futurLength = (players.length / 2) + ((players.length % 2 == 0) ? 0 : 1); while(players.length > futurLength){ players[randMod(players.length-1)] = players[players.length - 1]; players.pop(); } emit DayConflit(seasonIds.current(), futurLength, block.timestamp); players_ = players; } /** * @dev Selecting the winner of the war */ function lastDayFight() external onlyRole(DEFAULT_ADMIN_ROLE) { require(players.length == 3 || players.length == 2, "there are too many warriors left"); seasons[seasonIds.current()].winner = players[randMod(players.length-1)]; delete players; emit WinnerSeason(seasonIds.current(),seasons[seasonIds.current()].winner); } /** * @dev Get the number of warrior for a Pokumi * @return players_ list of all participants */ function getAllParticipants() view external returns (address[] memory players_){ return players; } /** * @dev Get the number of warrior for a Pokumi * @param _id The id of the Pokumi * @return oneArmy_ number of warrior the requested Pokumi */ function getArmy(string memory _id) view external returns (uint oneArmy_){ oneArmy_ = pokumiArmy[_id]; } /** * @dev Getter for the number of warriors in the current season * @return nbrWarrior_ the number of warrior */ function getNbrWarrior() external view returns(uint nbrWarrior_){ nbrWarrior_ = players.length; } /** * @dev Getter for the current season * @return currentSeason_ the number of the season */ function getCurrentSeason() external view returns (uint currentSeason_) { return seasonIds.current(); } /** * @dev calculate the number of days that a war will last * @param x the number of warriors participating in the war * @return r the number of days of the war */ function durationWar(uint x) internal pure returns (uint8 r) { require (x > 0); if (x >= 2**128) { x >>= 128; r += 128; } if (x >= 2**64) { x >>= 64; r += 64; } if (x >= 2**32) { x >>= 32; r += 32; } if (x >= 2**16) { x >>= 16; r += 16; } if (x >= 2**8) { x >>= 8; r += 8; } if (x >= 2**4) { x >>= 4; r += 4; } if (x >= 2**2) { x >>= 2; r += 2; } if (x >= 2**1) { x >>= 1; r += 1; } } /** * @dev Generates a random number * @param _modulus number to get max range * @return random_ a random number * */ function randMod(uint _modulus) internal returns(uint random_) { randNonce++; random_ = uint(keccak256(abi.encodePacked(block.timestamp,msg.sender,randNonce))) % _modulus; } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Pausable) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external virtual override returns (bytes4){ emit ReceivedERC1155(operator, from, id, value, data); return IERC1155Receiver.onERC1155Received.selector; } function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external virtual override returns (bytes4){ emit ReceivedBatchERC1155(operator, from, ids, values, data); return IERC1155Receiver.onERC1155Received.selector; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC1155,ERC1155Receiver, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } }
348
124
// Unlocks all avilable vAKRO for a holder holder Whose funds to unlockreturn total unlocked amount awailable for redeem /
function unlockAvailable(address holder) public returns (uint256) { require(holders[holder].batches.length > 0, "VestedAkro: nothing to unlock"); claimAllFromBatches(holder); return holders[holder].unlocked; }
function unlockAvailable(address holder) public returns (uint256) { require(holders[holder].batches.length > 0, "VestedAkro: nothing to unlock"); claimAllFromBatches(holder); return holders[holder].unlocked; }
35,690
46
// Changes weight to updatedWeight by reducing, pushes tokens and burns LP tokens. // function _moveWeightDown(
) internal { uint256 totalSupply_ = totalSupply; require( totalWeight.add(weight.sub(updatedWeight)) <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT" ); uint256 absoluteWeightChange = weight.sub(updatedWeight); uint256 absoluteBalanceChange = balance.mul(absoluteWeightChange.div(weight)); uint256 poolAmountIn = totalSupply_.mul(absoluteWeightChange.div(totalWeight)); require(balance.sub(absoluteBalanceChange) >= 10**5, "ERR_MIN_BALANCE"); optionPool_.rebind(token_, balance.sub(absoluteBalanceChange), updatedWeight); IERC20(token_).safeTransfer(msg.sender, absoluteBalanceChange); calibration.beginBlock = 0; _burnPoolShare(poolAmountIn); } */
) internal { uint256 totalSupply_ = totalSupply; require( totalWeight.add(weight.sub(updatedWeight)) <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT" ); uint256 absoluteWeightChange = weight.sub(updatedWeight); uint256 absoluteBalanceChange = balance.mul(absoluteWeightChange.div(weight)); uint256 poolAmountIn = totalSupply_.mul(absoluteWeightChange.div(totalWeight)); require(balance.sub(absoluteBalanceChange) >= 10**5, "ERR_MIN_BALANCE"); optionPool_.rebind(token_, balance.sub(absoluteBalanceChange), updatedWeight); IERC20(token_).safeTransfer(msg.sender, absoluteBalanceChange); calibration.beginBlock = 0; _burnPoolShare(poolAmountIn); } */
40,091
9
// If no restrictions were triggered return success
return SUCCESS_CODE;
return SUCCESS_CODE;
50,443
367
// Data
uint256 public cpi_last = 28012600000; // Dec 2021 CPI-U, 280.126 * 100000000 uint256 public cpi_target = 28193300000; // Jan 2022 CPI-U, 281.933 * 100000000 uint256 public peg_price_last = 1e18; // Use currPegPrice(). Will always be in Dec 2021 dollars uint256 public peg_price_target = 1006450668627688968; // Will always be in Dec 2021 dollars
uint256 public cpi_last = 28012600000; // Dec 2021 CPI-U, 280.126 * 100000000 uint256 public cpi_target = 28193300000; // Jan 2022 CPI-U, 281.933 * 100000000 uint256 public peg_price_last = 1e18; // Use currPegPrice(). Will always be in Dec 2021 dollars uint256 public peg_price_target = 1006450668627688968; // Will always be in Dec 2021 dollars
12,175
46
// pay outstanding interest to lender
_payInterest( loanLocal.lender, loanParamsLocal.loanToken ); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken]; uint256 owedPerDayRefund; if (closePrincipal < loanLocal.principal) {
_payInterest( loanLocal.lender, loanParamsLocal.loanToken ); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken]; uint256 owedPerDayRefund; if (closePrincipal < loanLocal.principal) {
42,983
75
// Update the balance proof data for the closing_participant
updateBalanceProofData(channel, closing_participant, nonce, balance_hash); emit NonClosingBalanceProofUpdated( channel_identifier, closing_participant, nonce, balance_hash );
updateBalanceProofData(channel, closing_participant, nonce, balance_hash); emit NonClosingBalanceProofUpdated( channel_identifier, closing_participant, nonce, balance_hash );
7,442
222
// Auction contract for collateral
address collateralAuction;
address collateralAuction;
33,911
3
// min cross transfer amount :token => min amount.
mapping(address => uint256) public minAmountLimit; modifier onlyFMarketOrAdmin(address token) { require(address(fluxMarkets[token]) == msg.sender || msg.sender == owner(), "ONLY_FOR_FLUXMARKET"); _; }
mapping(address => uint256) public minAmountLimit; modifier onlyFMarketOrAdmin(address token) { require(address(fluxMarkets[token]) == msg.sender || msg.sender == owner(), "ONLY_FOR_FLUXMARKET"); _; }
35,967
226
// calculates the fee of given value. _value the value of the transaction to calculate fees from _sender address sending._recipient address receiving.return the transactional fee for given value /
function getTxFees( uint256 _value, address _sender, address _recipient
function getTxFees( uint256 _value, address _sender, address _recipient
49,509
83
// View Methods Start // This function is used to get the minimum staking amount /
function getMinimumStakingAmount() external view returns (uint256) { return _minimumStakingAmount; }
function getMinimumStakingAmount() external view returns (uint256) { return _minimumStakingAmount; }
44,988
5
// We whitelist the pair to have no vesting on reception
governance = msg.sender; // bypass !gov checks _PAIR_ADDRESS = uniswapPair; setNoVestingWhitelist(uniswapPair, true); setNoVestingWhitelist(BURNER, true); setNoVestingWhitelist(rebasingLP, true); setNoVestingWhitelist(UNISWAP_V2_ROUTER, true); // We set the router to no vesting so we dont need to check it in the balance handler to return maxbalance.
governance = msg.sender; // bypass !gov checks _PAIR_ADDRESS = uniswapPair; setNoVestingWhitelist(uniswapPair, true); setNoVestingWhitelist(BURNER, true); setNoVestingWhitelist(rebasingLP, true); setNoVestingWhitelist(UNISWAP_V2_ROUTER, true); // We set the router to no vesting so we dont need to check it in the balance handler to return maxbalance.
41,075
22
// modifier to limit the minting to not exceed maximum supply limit
modifier canPoSMint() { require(totalSupply < maxTotalSupply); _; }
modifier canPoSMint() { require(totalSupply < maxTotalSupply); _; }
25,441
129
// The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) }
assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) }
5,157
41
// new v.12.7 patient_address stored as bytes:
// function getAddressFromBytesToString(uint256 tokenId) public view returns (string memory) { // Script storage rx = allScripts[tokenId]; // return string(abi.encodePacked(rx.patient_address)); // }
// function getAddressFromBytesToString(uint256 tokenId) public view returns (string memory) { // Script storage rx = allScripts[tokenId]; // return string(abi.encodePacked(rx.patient_address)); // }
14,627
84
// mint HXY to address ( for use in external contracts within the eco-system)
function mintHXY(uint hearts, address receiver) public onlyMinters returns(bool)
function mintHXY(uint hearts, address receiver) public onlyMinters returns(bool)
32,939
29
// Destroy tokens from owners account /
function burnTokens(address _addr, uint256 _amount)public onlyOwner { require (balances[msg.sender] < _amount); // Throw if you do not have enough balance totalRemainSupply += _amount; // Deduct totalSupply balances[_addr] -= _amount; // Destroy coins on senders wallet burnToken(_addr, _amount); // Raise Burn event Transfer(_addr, 0x0, _amount); // Raise transfer to 0x0 }
function burnTokens(address _addr, uint256 _amount)public onlyOwner { require (balances[msg.sender] < _amount); // Throw if you do not have enough balance totalRemainSupply += _amount; // Deduct totalSupply balances[_addr] -= _amount; // Destroy coins on senders wallet burnToken(_addr, _amount); // Raise Burn event Transfer(_addr, 0x0, _amount); // Raise transfer to 0x0 }
11,899
71
// ============ R = 1 cases ============
function _ROneSellBaseToken(PMMState memory state, uint256 payBaseAmount) internal pure returns ( uint256 // receiveQuoteToken )
function _ROneSellBaseToken(PMMState memory state, uint256 payBaseAmount) internal pure returns ( uint256 // receiveQuoteToken )
19,396
158
// Checks if a yield token is enabled.//yieldToken The address of the yield token.
function _checkYieldTokenEnabled(address yieldToken) internal view { if (!_yieldTokens[yieldToken].enabled) { revert TokenDisabled(yieldToken); } }
function _checkYieldTokenEnabled(address yieldToken) internal view { if (!_yieldTokens[yieldToken].enabled) { revert TokenDisabled(yieldToken); } }
44,178
318
// Rebuild the resolver caches in all MixinResolver contracts - batch 1;
MixinResolver[] memory addressresolver_rebuildCaches_destinations_1_0 = new MixinResolver[](20); addressresolver_rebuildCaches_destinations_1_0[0] = MixinResolver(0xDA4eF8520b1A57D7d63f1E249606D1A459698876); addressresolver_rebuildCaches_destinations_1_0[1] = MixinResolver(0xAD95C918af576c82Df740878C3E983CBD175daB6); addressresolver_rebuildCaches_destinations_1_0[2] = MixinResolver(0xcf9E60005C9aca983caf65d3669a24fDd0775fc0); addressresolver_rebuildCaches_destinations_1_0[3] = MixinResolver(new_Exchanger_contract); addressresolver_rebuildCaches_destinations_1_0[4] = MixinResolver(0xB774711F0BC1306ce892ef8C02D0476dCccB46B7); addressresolver_rebuildCaches_destinations_1_0[5] = MixinResolver(0x62922670313bf6b41C580143d1f6C173C5C20019); addressresolver_rebuildCaches_destinations_1_0[6] = MixinResolver(0xCd9D4988C0AE61887B075bA77f08cbFAd2b65068); addressresolver_rebuildCaches_destinations_1_0[7] = MixinResolver(0xd69b189020EF614796578AfE4d10378c5e7e1138); addressresolver_rebuildCaches_destinations_1_0[8] = MixinResolver(new_Synthetix_contract);
MixinResolver[] memory addressresolver_rebuildCaches_destinations_1_0 = new MixinResolver[](20); addressresolver_rebuildCaches_destinations_1_0[0] = MixinResolver(0xDA4eF8520b1A57D7d63f1E249606D1A459698876); addressresolver_rebuildCaches_destinations_1_0[1] = MixinResolver(0xAD95C918af576c82Df740878C3E983CBD175daB6); addressresolver_rebuildCaches_destinations_1_0[2] = MixinResolver(0xcf9E60005C9aca983caf65d3669a24fDd0775fc0); addressresolver_rebuildCaches_destinations_1_0[3] = MixinResolver(new_Exchanger_contract); addressresolver_rebuildCaches_destinations_1_0[4] = MixinResolver(0xB774711F0BC1306ce892ef8C02D0476dCccB46B7); addressresolver_rebuildCaches_destinations_1_0[5] = MixinResolver(0x62922670313bf6b41C580143d1f6C173C5C20019); addressresolver_rebuildCaches_destinations_1_0[6] = MixinResolver(0xCd9D4988C0AE61887B075bA77f08cbFAd2b65068); addressresolver_rebuildCaches_destinations_1_0[7] = MixinResolver(0xd69b189020EF614796578AfE4d10378c5e7e1138); addressresolver_rebuildCaches_destinations_1_0[8] = MixinResolver(new_Synthetix_contract);
71,336
59
// Claim N bought tokens to the investor as the msg sender
function claim() { address investor = msg.sender; if(balances[investor] == 0) { // Not our investor throw; } if(now < freezeEndsAt[investor]) { throw; // Trying to claim early } uint amount = balances[investor]; balances[investor] = 0; claimed[investor] = claimed[investor].plus(amount); totalClaimed = totalClaimed.plus(amount); token.transfer(investor, amount); Distributed(investor, amount); }
function claim() { address investor = msg.sender; if(balances[investor] == 0) { // Not our investor throw; } if(now < freezeEndsAt[investor]) { throw; // Trying to claim early } uint amount = balances[investor]; balances[investor] = 0; claimed[investor] = claimed[investor].plus(amount); totalClaimed = totalClaimed.plus(amount); token.transfer(investor, amount); Distributed(investor, amount); }
41,461
53
// Set a value in a tree./_key The key of the tree./_value The new value./_ID The ID of the value./ `O(log_k(n))` where/ `k` is the maximum number of children per node in the tree,/and `n` is the maximum number of nodes ever appended.
function _set(bytes32 _key, uint256 _value, bytes32 _ID) internal { SortitionSumTree storage tree = sortitionSumTrees[_key]; uint256 treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint256 parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint256 newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.pop(); tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; _updateParents(_key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint256 value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; _updateParents(_key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint256 plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; _updateParents(_key, treeIndex, plusOrMinus, plusOrMinusValue); } } }
function _set(bytes32 _key, uint256 _value, bytes32 _ID) internal { SortitionSumTree storage tree = sortitionSumTrees[_key]; uint256 treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint256 parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint256 newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.pop(); tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; _updateParents(_key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint256 value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; _updateParents(_key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint256 plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; _updateParents(_key, treeIndex, plusOrMinus, plusOrMinusValue); } } }
21,015
76
// Initiate a change of owner to `_owner`
function changeOwner(address _owner) public onlyOwner returns (bool)
function changeOwner(address _owner) public onlyOwner returns (bool)
53,234
29
// Returns true if this token is claimable, meaning it can have or actually have _maximumEditions[tokenId] > 1/
function isClaimable(uint256 tokenId) external view returns (bool) { require(_exists(tokenId), 'setTokenClaimStartPrice: Nonexisting token.'); if(_maximumEditions[tokenId] > 1) { return true; } else{ return false; } }
function isClaimable(uint256 tokenId) external view returns (bool) { require(_exists(tokenId), 'setTokenClaimStartPrice: Nonexisting token.'); if(_maximumEditions[tokenId] > 1) { return true; } else{ return false; } }
40,707
5
// ============ Private Functions ============ /
function _getProposalInfo(uint256 _proposalId) internal view returns (address, uint256[3] memory) { (, address proposer, , , uint256 endBlock, uint256 forVotes, uint256 againstVotes, , , ) = governor.proposals(_proposalId); return (proposer, [endBlock, forVotes.sub(againstVotes), uint256(governor.state(_proposalId))]); }
function _getProposalInfo(uint256 _proposalId) internal view returns (address, uint256[3] memory) { (, address proposer, , , uint256 endBlock, uint256 forVotes, uint256 againstVotes, , , ) = governor.proposals(_proposalId); return (proposer, [endBlock, forVotes.sub(againstVotes), uint256(governor.state(_proposalId))]); }
35,497
35
// FPT-B = Staked FNX
function fnxUnStakeFPT_B(uint256 FPT_B_amount) public onlyByOwnerOrGovernance { fnxMinePool.unstakeFPTB(FPT_B_amount); }
function fnxUnStakeFPT_B(uint256 FPT_B_amount) public onlyByOwnerOrGovernance { fnxMinePool.unstakeFPTB(FPT_B_amount); }
74,564
229
// order irrelevant in other case
order = [uint256(0), 1, 2];
order = [uint256(0), 1, 2];
72,032
39
// Prevents a contract from calling itself, directly or indirectly. If you mark a function `nonReentrant`, you should also mark it `external`. Calling one `nonReentrant` function from another is not supported. Instead, you can implement a `private` function doing the actual work, and an `external` wrapper marked as `nonReentrant`./
modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; }
modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; }
10,916
21
// Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred /
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
26,720
4
// Initializer variant that does not embed linearized calls to any parent initializers. Follows the multiple inheritance initializer rules defined [here](calling two of these init functions can potentially initialize the same contract twice. /
function __NORI_init_unchained() internal onlyInitializing { // solhint-disable-previous-line no-empty-blocks, func-name-mixedcase }
function __NORI_init_unchained() internal onlyInitializing { // solhint-disable-previous-line no-empty-blocks, func-name-mixedcase }
56,135
197
// manual antibot, play fair!
function _blacklistBot(address account) external onlyOwner() { require(account != 0x10ED43C718714eb63d5aA57B78B54704E256024E, 'We cannot blacklist Pancakeswap'); require(!_isBot[account], "Account is already blacklisted"); _isBot[account] = true; _confirmedBots.push(account); }
function _blacklistBot(address account) external onlyOwner() { require(account != 0x10ED43C718714eb63d5aA57B78B54704E256024E, 'We cannot blacklist Pancakeswap'); require(!_isBot[account], "Account is already blacklisted"); _isBot[account] = true; _confirmedBots.push(account); }
27,521